From 968df21ef04ae5502cd511cf63ea0711bfdaa81f Mon Sep 17 00:00:00 2001 From: PiggyPiglet Date: Mon, 17 Nov 2025 14:11:21 +0800 Subject: [PATCH] we're really getting somewhere!@1 who the fuck decided to use 2 space instead of 4 --- build.gradle.kts | 8 +- .../clip/placeholderapi/PAPIComponents.java | 121 ++ .../clip/placeholderapi/PlaceholderAPI.java | 1094 ++++++++--------- .../placeholderapi/PlaceholderAPIPlugin.java | 424 +++---- .../clip/placeholderapi/PlaceholderHook.java | 9 - .../commands/PlaceholderCommand.java | 114 +- .../commands/PlaceholderCommandRouter.java | 148 +-- .../placeholderapi/commands/TestCommand.java | 51 + .../commands/impl/cloud/CommandECloud.java | 186 +-- .../impl/cloud/CommandECloudClear.java | 23 +- .../impl/cloud/CommandECloudDownload.java | 175 +-- .../cloud/CommandECloudExpansionInfo.java | 169 +-- .../cloud/CommandECloudExpansionList.java | 530 ++++---- .../CommandECloudExpansionPlaceholders.java | 104 +- .../impl/cloud/CommandECloudRefresh.java | 23 +- .../impl/cloud/CommandECloudStatus.java | 55 +- .../impl/cloud/CommandECloudUpdate.java | 154 +-- .../commands/impl/local/CommandDump.java | 268 ++-- .../impl/local/CommandExpansionRegister.java | 123 +- .../local/CommandExpansionUnregister.java | 69 +- .../commands/impl/local/CommandHelp.java | 69 +- .../commands/impl/local/CommandInfo.java | 143 +-- .../commands/impl/local/CommandList.java | 42 +- .../commands/impl/local/CommandParse.java | 385 +++--- .../commands/impl/local/CommandReload.java | 19 +- .../commands/impl/local/CommandVersion.java | 29 +- .../events/ExpansionRegisterEvent.java | 92 +- .../events/ExpansionUnregisterEvent.java | 56 +- .../events/ExpansionsLoadedEvent.java | 15 +- .../events/PlaceholderHookUnloadEvent.java | 56 +- .../placeholderapi/expansion/Version.java | 30 +- .../expansion/cloud/CloudExpansion.java | 309 ++--- .../manager/CloudExpansionManager.java | 350 +++--- .../manager/LocalExpansionManager.java | 767 ++++++------ .../replacer/CharsReplacer.java | 203 +-- .../replacer/ComponentCharsReplacer.java | 303 ----- .../replacer/ComponentReplacer.java | 146 +++ .../replacer/ExactReplacer.java | 48 + .../placeholderapi/replacer/Replacer.java | 23 +- .../me/clip/placeholderapi/util/FileUtil.java | 68 +- .../me/clip/placeholderapi/util/Format.java | 53 +- .../me/clip/placeholderapi/util/Futures.java | 64 +- .../java/me/clip/placeholderapi/util/Msg.java | 81 +- .../clip/placeholderapi/util/TimeFormat.java | 8 +- .../me/clip/placeholderapi/util/TimeUtil.java | 118 +- src/main/resources/plugin.yml | 2 + 46 files changed, 3711 insertions(+), 3616 deletions(-) create mode 100644 src/main/java/me/clip/placeholderapi/PAPIComponents.java create mode 100644 src/main/java/me/clip/placeholderapi/commands/TestCommand.java delete mode 100644 src/main/java/me/clip/placeholderapi/replacer/ComponentCharsReplacer.java create mode 100644 src/main/java/me/clip/placeholderapi/replacer/ComponentReplacer.java create mode 100644 src/main/java/me/clip/placeholderapi/replacer/ExactReplacer.java diff --git a/build.gradle.kts b/build.gradle.kts index c2702b1..13743e5 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -28,6 +28,7 @@ dependencies { implementation("net.kyori:adventure-platform-bukkit:4.4.1") //compileOnly("org.spigotmc:spigot-api:1.21-R0.1-SNAPSHOT") + compileOnly("io.papermc.paper:paper-api:1.21.10-R0.1-SNAPSHOT") compileOnly("dev.folia:folia-api:1.20.1-R0.1-SNAPSHOT") compileOnlyApi("org.jetbrains:annotations:23.0.0") @@ -92,7 +93,12 @@ tasks { archiveClassifier.set("") relocate("org.bstats", "me.clip.placeholderapi.metrics") - relocate("net.kyori", "me.clip.placeholderapi.libs.kyori") +// relocate("net.kyori", "me.clip.placeholderapi.libs.kyori") { +// exclude("me/clip/placeholderapi/PAPIComponents.java") +// exclude("me/clip/placeholderapi/commands/TestCommand.java") +// } + + destinationDirectory = file("server/1.21/plugins/") exclude("META-INF/versions/**") } diff --git a/src/main/java/me/clip/placeholderapi/PAPIComponents.java b/src/main/java/me/clip/placeholderapi/PAPIComponents.java new file mode 100644 index 0000000..a81ad9c --- /dev/null +++ b/src/main/java/me/clip/placeholderapi/PAPIComponents.java @@ -0,0 +1,121 @@ +package me.clip.placeholderapi; + +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.Relational; +import me.clip.placeholderapi.replacer.ExactReplacer; +import me.clip.placeholderapi.replacer.Replacer; +import net.kyori.adventure.text.Component; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.checkerframework.checker.units.qual.N; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public final class PAPIComponents { + private static final Replacer EXACT_REPLACER = new ExactReplacer(); + + @NotNull + public static Component setPlaceholders(final OfflinePlayer player, @NotNull final Component component) { + // TODO: explore a custom TextReplacementRenderer which doesn't use regex for performance benefits i.e. merge CharsReplacer with kyori TextReplacementRenderer + return component.replaceText(config -> config.match(PlaceholderAPI.PLACEHOLDER_PATTERN).replacement((result, builder) -> + builder.content(EXACT_REPLACER.apply(result.group(), player, PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion)))); + } + + @NotNull + public static List setPlaceholders(final OfflinePlayer player, @NotNull final List components) { + return components.stream().map(component -> setPlaceholders(player, component)).collect(Collectors.toList()); + } + + @NotNull + public static Component setPlaceholders(final Player player, @NotNull final Component component) { + return setPlaceholders((OfflinePlayer) player, component); + } + + @NotNull + public static List setPlaceholders(final Player player, @NotNull final List components) { + return setPlaceholders((OfflinePlayer) player, components); + } + + @NotNull + public static Component setBracketPlaceholders(final OfflinePlayer player, @NotNull final Component component) { + return component.replaceText(config -> config.match(PlaceholderAPI.BRACKET_PLACEHOLDER_PATTERN).replacement((result, builder) -> + builder.content(EXACT_REPLACER.apply(result.group(), player, PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion)))); + } + + @NotNull + public static List setBracketPlaceholders(final OfflinePlayer player, @NotNull final List components) { + return components.stream().map(component -> setBracketPlaceholders(player, component)).collect(Collectors.toList()); + } + + @NotNull + public static Component setBracketPlaceholders(final Player player, @NotNull final Component component) { + return setBracketPlaceholders((OfflinePlayer) player, component); + } + + @NotNull + public static List setBracketPlaceholders(final Player player, @NotNull final List components) { + return setBracketPlaceholders((OfflinePlayer) player, components); + } + +// public static Component setRelationalPlaceholders(Player one, Player two, Component component) { +// return component.replaceText(config -> config.match(PlaceholderAPI.RELATIONAL_PLACEHOLDER_PATTERN).replacement((result, builder) -> { +// +// final String format = result.group(2); +// final int index = format.indexOf("_"); +// +// if (index <= 0 || index >= format.length()) { +// continue; +// } +// +// String identifier = format.substring(0, index).toLowerCase(Locale.ROOT); +// String params = format.substring(index + 1); +// final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() +// .getLocalExpansionManager().getExpansion(identifier); +// +// if (!(expansion instanceof Relational)) { +// continue; +// } +// +// final String value = ((Relational) expansion).onPlaceholderRequest(one, two, params); +// +// if (value != null) { +// text = text.replaceAll(Pattern.quote(matcher.group()), Matcher.quoteReplacement(value)); +// } +// +// +// })); +// +// final Matcher matcher = PlaceholderAPI.RELATIONAL_PLACEHOLDER_PATTERN.matcher(text); +// +// while (matcher.find()) { +// final String format = matcher.group(2); +// final int index = format.indexOf("_"); +// +// if (index <= 0 || index >= format.length()) { +// continue; +// } +// +// String identifier = format.substring(0, index).toLowerCase(Locale.ROOT); +// String params = format.substring(index + 1); +// final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() +// .getLocalExpansionManager().getExpansion(identifier); +// +// if (!(expansion instanceof Relational)) { +// continue; +// } +// +// final String value = ((Relational) expansion).onPlaceholderRequest(one, two, params); +// +// if (value != null) { +// text = text.replaceAll(Pattern.quote(matcher.group()), Matcher.quoteReplacement(value)); +// } +// } +// +// return text; +// } +} diff --git a/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java b/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java index a138c9a..8644555 100644 --- a/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java +++ b/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java @@ -34,9 +34,8 @@ import me.clip.placeholderapi.expansion.manager.LocalExpansionManager; import me.clip.placeholderapi.replacer.CharsReplacer; import me.clip.placeholderapi.replacer.Replacer; import me.clip.placeholderapi.replacer.Replacer.Closure; +import me.clip.placeholderapi.replacer.ExactReplacer; import me.clip.placeholderapi.util.Msg; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.TextReplacementConfig; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; @@ -45,588 +44,583 @@ import org.jetbrains.annotations.NotNull; public final class PlaceholderAPI { - private static final Replacer REPLACER_PERCENT = new CharsReplacer(Closure.PERCENT); - private static final Replacer REPLACER_BRACKET = new CharsReplacer(Closure.BRACKET); + private static final Replacer REPLACER_PERCENT = new CharsReplacer(Closure.PERCENT); + private static final Replacer REPLACER_BRACKET = new CharsReplacer(Closure.BRACKET); - private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("[%]([^%]+)[%]"); - private static final Pattern BRACKET_PLACEHOLDER_PATTERN = Pattern.compile("[{]([^{}]+)[}]"); - private static final Pattern RELATIONAL_PLACEHOLDER_PATTERN = Pattern - .compile("[%](rel_)([^%]+)[%]"); + static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("[%]([^%]+)[%]"); + static final Pattern BRACKET_PLACEHOLDER_PATTERN = Pattern.compile("[{]([^{}]+)[}]"); + static final Pattern RELATIONAL_PLACEHOLDER_PATTERN = Pattern + .compile("[%](rel_)([^%]+)[%]"); + private static final Replacer TEST = new ExactReplacer(); - private PlaceholderAPI() { - } - - // === Current API === - - @NotNull - public static Component setComponentPlaceholders(final OfflinePlayer player, @NotNull final Component component) { - // change charsreplacer to custom that returns component instead of string - this is going to suck mega - return component.replaceText(config -> config.match(PLACEHOLDER_PATTERN).replacement((result, builder) -> builder.content(REPLACER_PERCENT.apply(builder.content(), player, PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion)))); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal %_%}. - * - * @param player Player to parse the placeholders against - * @param text Text to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static String setPlaceholders(final OfflinePlayer player, - @NotNull final String text) { - return REPLACER_PERCENT.apply(text, player, - PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal %_%}. - * - * @param player Player to parse the placeholders against - * @param text List of Strings to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static List setPlaceholders(final OfflinePlayer player, - @NotNull final List text) { - return text.stream().map(line -> setPlaceholders(player, line)).collect(Collectors.toList()); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal %_%}. - * - * @param player Player to parse the placeholders against - * @param text Text to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static String setPlaceholders(final Player player, @NotNull String text) { - return setPlaceholders(((OfflinePlayer) player), text); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal %_%}. - * - * @param player Player to parse the placeholders against - * @param text List of Strings to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static List setPlaceholders(final Player player, @NotNull List<@NotNull String> text) { - return setPlaceholders(((OfflinePlayer) player), text); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal {_}}. - * - * @param player Player to parse the placeholders against - * @param text Text to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static String setBracketPlaceholders(final OfflinePlayer player, - @NotNull final String text) { - return REPLACER_BRACKET.apply(text, player, - PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal {_}}. - * - * @param player Player to parse the placeholders against - * @param text List of Strings to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static List<@NotNull String> setBracketPlaceholders(final OfflinePlayer player, - @NotNull final List<@NotNull String> text) { - return text.stream().map(line -> setBracketPlaceholders(player, line)) - .collect(Collectors.toList()); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal {_}}. - * - * @param player Player to parse the placeholders against - * @param text Text to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static String setBracketPlaceholders(Player player, @NotNull String text) { - return setBracketPlaceholders((OfflinePlayer) player, text); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal {_}}. - * - * @param player Player to parse the placeholders against - * @param text List of Strings to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static List setBracketPlaceholders(Player player, @NotNull List text) { - return setBracketPlaceholders((OfflinePlayer) player, text); - } - - /** - * set relational placeholders in the text specified placeholders are matched with the pattern - * {@literal %%} when set with this method - * - * @param one First player to compare - * @param two Second player to compare - * @param text Text to parse the placeholders in - * @return The text containing the parsed relational placeholders - */ - public static String setRelationalPlaceholders(Player one, Player two, String text) { - final Matcher matcher = RELATIONAL_PLACEHOLDER_PATTERN.matcher(text); - - while (matcher.find()) { - final String format = matcher.group(2); - final int index = format.indexOf("_"); - - if (index <= 0 || index >= format.length()) { - continue; - } - - String identifier = format.substring(0, index).toLowerCase(Locale.ROOT); - String params = format.substring(index + 1); - final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() - .getLocalExpansionManager().getExpansion(identifier); - - if (!(expansion instanceof Relational)) { - continue; - } - - final String value = ((Relational) expansion).onPlaceholderRequest(one, two, params); - - if (value != null) { - text = text.replaceAll(Pattern.quote(matcher.group()), Matcher.quoteReplacement(value)); - } + private PlaceholderAPI() { } - return text; - } + // === Current API === - /** - * Translate placeholders in the provided List based on the relation of the two provided players. - *
The pattern of a valid placeholder is {@literal %rel__%}. - * - * @param one Player to compare - * @param two Player to compare - * @param text text to parse the placeholder values to - * @return The text containing the parsed relational placeholders - */ - public static List setRelationalPlaceholders(Player one, Player two, List text) { - return text.stream().map(line -> setRelationalPlaceholders(one, two, line)) - .collect(Collectors.toList()); - } + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal %_%}. + * + * @param player Player to parse the placeholders against + * @param text Text to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static String setPlaceholders(final OfflinePlayer player, + @NotNull final String text) { + return REPLACER_PERCENT.apply(text, player, + PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion); + } - /** - * Check if a specific placeholder identifier is currently registered - * - * @param identifier The identifier to check - * @return true if identifier is already registered - */ - public static boolean isRegistered(@NotNull final String identifier) { - return PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() - .findExpansionByIdentifier(identifier).isPresent(); - } + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal %_%}. + * + * @param player Player to parse the placeholders against + * @param text List of Strings to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static List setPlaceholders(final OfflinePlayer player, + @NotNull final List text) { + return text.stream().map(line -> setPlaceholders(player, line)).collect(Collectors.toList()); + } - /** - * Get all registered placeholder identifiers - * - * @return A Set of type String containing the identifiers of all registered expansions. - */ - @NotNull - public static Set getRegisteredIdentifiers() { - return ImmutableSet - .copyOf(PlaceholderAPIPlugin.getInstance().getLocalExpansionManager().getIdentifiers()); - } + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal %_%}. + * + * @param player Player to parse the placeholders against + * @param text Text to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static String setPlaceholders(final Player player, @NotNull String text) { + return setPlaceholders(((OfflinePlayer) player), text); + } - /** - * Get the normal placeholder pattern. - * - * @return Regex Pattern of {@literal [%]([^%]+)[%]} - */ - public static Pattern getPlaceholderPattern() { - return PLACEHOLDER_PATTERN; - } + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal %_%}. + * + * @param player Player to parse the placeholders against + * @param text List of Strings to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static List setPlaceholders(final Player player, @NotNull List<@NotNull String> text) { + return setPlaceholders(((OfflinePlayer) player), text); + } - /** - * Get the bracket placeholder pattern. - * - * @return Regex Pattern of {@literal [{]([^{}]+)[}]} - */ - public static Pattern getBracketPlaceholderPattern() { - return BRACKET_PLACEHOLDER_PATTERN; - } + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal {_}}. + * + * @param player Player to parse the placeholders against + * @param text Text to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static String setBracketPlaceholders(final OfflinePlayer player, + @NotNull final String text) { + return REPLACER_BRACKET.apply(text, player, + PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion); + } - /** - * Get the relational placeholder pattern. - * - * @return Regex Pattern of {@literal [%](rel_)([^%]+)[%]} - */ - public static Pattern getRelationalPlaceholderPattern() { - return RELATIONAL_PLACEHOLDER_PATTERN; - } + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal {_}}. + * + * @param player Player to parse the placeholders against + * @param text List of Strings to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static List<@NotNull String> setBracketPlaceholders(final OfflinePlayer player, + @NotNull final List<@NotNull String> text) { + return text.stream().map(line -> setBracketPlaceholders(player, line)) + .collect(Collectors.toList()); + } - /** - * Check if a String contains any PlaceholderAPI placeholders ({@literal - * %_%}). - * - * @param text String to check - * @return true if String contains any matches to the normal placeholder pattern, false otherwise - */ - public static boolean containsPlaceholders(String text) { - return text != null && PLACEHOLDER_PATTERN.matcher(text).find(); - } + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal {_}}. + * + * @param player Player to parse the placeholders against + * @param text Text to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static String setBracketPlaceholders(Player player, @NotNull String text) { + return setBracketPlaceholders((OfflinePlayer) player, text); + } - /** - * Check if a String contains any PlaceholderAPI bracket placeholders ({@literal - * {_}}). - * - * @param text String to check - * @return true if String contains any matches to the bracket placeholder pattern, false otherwise - */ - public static boolean containsBracketPlaceholders(String text) { - return text != null && BRACKET_PLACEHOLDER_PATTERN.matcher(text).find(); - } + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal {_}}. + * + * @param player Player to parse the placeholders against + * @param text List of Strings to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static List setBracketPlaceholders(Player player, @NotNull List text) { + return setBracketPlaceholders((OfflinePlayer) player, text); + } - // === Deprecated API === + /** + * set relational placeholders in the text specified placeholders are matched with the pattern + * {@literal %%} when set with this method + * + * @param one First player to compare + * @param two Second player to compare + * @param text Text to parse the placeholders in + * @return The text containing the parsed relational placeholders + */ + public static String setRelationalPlaceholders(Player one, Player two, String text) { + final Matcher matcher = RELATIONAL_PLACEHOLDER_PATTERN.matcher(text); - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static boolean registerExpansion(PlaceholderExpansion expansion) - { - return expansion.register(); - } + while (matcher.find()) { + final String format = matcher.group(2); + final int index = format.indexOf("_"); - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static boolean unregisterExpansion(PlaceholderExpansion expansion) - { - return expansion.unregister(); - } + if (index <= 0 || index >= format.length()) { + continue; + } - /** - * Get map of registered placeholders - * - * @deprecated Use {@link LocalExpansionManager#getExpansions()} instead. - * - * @return Map of registered placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static Map getPlaceholders() { - return PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() - .getExpansions().stream() - .collect(Collectors.toMap(PlaceholderExpansion::getIdentifier, ex -> ex)); - } + String identifier = format.substring(0, index).toLowerCase(Locale.ROOT); + String params = format.substring(index + 1); + final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() + .getLocalExpansionManager().getExpansion(identifier); - /** - * @deprecated Please use {@link PlaceholderExpansion} to - * register placeholders instead - * - * @param plugin The Plugin to register with this {@link PlaceholderHook} - * @param placeholderHook The {@link PlaceholderHook} to register - * @return always false - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static boolean registerPlaceholderHook(Plugin plugin, PlaceholderHook placeholderHook) { - Msg.warn("Nag author(s) %s of plugin %s about their usage of the deprecated PlaceholderHook" - + " class! This class will be removed in v2.13.0!", plugin.getDescription().getAuthors(), - plugin.getName()); - return false; - } + if (!(expansion instanceof Relational)) { + continue; + } - /** - * @deprecated Please use {@link PlaceholderExpansion} to - * register placeholders instead - * - * @param identifier The identifier to use for the {@link PlaceholderHook} - * @param placeholderHook The {@link PlaceholderHook} to register - * @return always false - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static boolean registerPlaceholderHook(String identifier, - PlaceholderHook placeholderHook) { - Msg.warn("%s is attempting to register placeholders via deprecated PlaceholderHook class." - + " This class is no longer supported and will be removed in v2.13.0!", identifier); - return false; - } + final String value = ((Relational) expansion).onPlaceholderRequest(one, two, params); - /** - * @deprecated Please use {@link PlaceholderExpansion} to - * unregister placeholders instead - * - * @param plugin The plugin to unregister - * @return always false - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static boolean unregisterPlaceholderHook(Plugin plugin) { - Msg.warn("Nag author(s) %s of plugin %s about their usage of the PlaceholderAPI class." - + " This way of unregistering placeholders is no longer supported and will be removed" - + " in v2.13.0!", plugin.getDescription().getAuthors(), plugin.getName()); - return false; - } + if (value != null) { + text = text.replaceAll(Pattern.quote(matcher.group()), Matcher.quoteReplacement(value)); + } + } - /** - * @deprecated Please use {@link PlaceholderExpansion} to - * unregister placeholders instead - * - * @param identifier The identifier to unregister - * @return always false - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static boolean unregisterPlaceholderHook(String identifier) { - Msg.warn("%s is attempting to unregister placeholders via PlaceholderAPI class." - + " This way of unregistering placeholders is no longer supported and will be removed" - + " in v2.13.0!", identifier); - return false; - } + return text; + } - /** - * @deprecated Will be removed in a future release. - * - * @return Set of registered identifiers - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static Set getRegisteredPlaceholderPlugins() { - return getRegisteredIdentifiers(); - } + /** + * Translate placeholders in the provided List based on the relation of the two provided players. + *
The pattern of a valid placeholder is {@literal %rel__%}. + * + * @param one Player to compare + * @param two Player to compare + * @param text text to parse the placeholder values to + * @return The text containing the parsed relational placeholders + */ + public static List setRelationalPlaceholders(Player one, Player two, List text) { + return text.stream().map(line -> setRelationalPlaceholders(one, two, line)) + .collect(Collectors.toList()); + } - /** - * @deprecated Will be removed in a future release. - * - * @return always null - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static Set getExternalPlaceholderPlugins() { - return null; - } + /** + * Check if a specific placeholder identifier is currently registered + * + * @param identifier The identifier to check + * @return true if identifier is already registered + */ + public static boolean isRegistered(@NotNull final String identifier) { + return PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() + .findExpansionByIdentifier(identifier).isPresent(); + } - /** - * @deprecated Please use {@link #setPlaceholders(OfflinePlayer, String)} instead - * - * @param player The offline player to parse the placeholders against - * @param text The text to parse - * @param pattern The Pattern to use - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setPlaceholders(OfflinePlayer player, - String text, Pattern pattern, boolean colorize) { - return setPlaceholders(player, text); - } + /** + * Get all registered placeholder identifiers + * + * @return A Set of type String containing the identifiers of all registered expansions. + */ + @NotNull + public static Set getRegisteredIdentifiers() { + return ImmutableSet + .copyOf(PlaceholderAPIPlugin.getInstance().getLocalExpansionManager().getIdentifiers()); + } - /** - * @deprecated Please use {@link #setPlaceholders(OfflinePlayer, List)} instead - * - * @param player The offline player to parse the placeholders against - * @param text The List of text to parse - * @param pattern The Pattern to use - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setPlaceholders(OfflinePlayer player, - List text, Pattern pattern, boolean colorize) { - return setPlaceholders(player, text); - } + /** + * Get the normal placeholder pattern. + * + * @return Regex Pattern of {@literal [%]([^%]+)[%]} + */ + public static Pattern getPlaceholderPattern() { + return PLACEHOLDER_PATTERN; + } - /** - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, List)} instead. - * - * @param player The offline player to parse the placeholders against - * @param text The List of text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setPlaceholders(OfflinePlayer player, List text, - boolean colorize) { - return setPlaceholders(player, text); - } + /** + * Get the bracket placeholder pattern. + * + * @return Regex Pattern of {@literal [{]([^{}]+)[}]} + */ + public static Pattern getBracketPlaceholderPattern() { + return BRACKET_PLACEHOLDER_PATTERN; + } - /** - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, List)} instead. - * - * @param player The offline player to parse the placeholders against - * @param text The List of text to parse - * @param pattern The Pattern to use - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setPlaceholders(OfflinePlayer player, List text, - Pattern pattern) { - return setPlaceholders(player, text); - } - /** - * @deprecated Will be removed in a future release. - * - * @param player The offline player to parse the placeholders against - * @param text The text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setPlaceholders(Player player, String text, boolean colorize) { - return setPlaceholders(player, text); - } + /** + * Get the relational placeholder pattern. + * + * @return Regex Pattern of {@literal [%](rel_)([^%]+)[%]} + */ + public static Pattern getRelationalPlaceholderPattern() { + return RELATIONAL_PLACEHOLDER_PATTERN; + } - /** - * @deprecated Will be removed in a future release. - * - * @param player The offline player to parse the placeholders against - * @param text The List of text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setPlaceholders(Player player, List text, boolean colorize) { - return setPlaceholders(player, text); - } + /** + * Check if a String contains any PlaceholderAPI placeholders ({@literal + * %_%}). + * + * @param text String to check + * @return true if String contains any matches to the normal placeholder pattern, false otherwise + */ + public static boolean containsPlaceholders(String text) { + return text != null && PLACEHOLDER_PATTERN.matcher(text).find(); + } - /** - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. - * - * @param player The offline player to parse the placeholders against - * @param text The text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setPlaceholders(OfflinePlayer player, String text, boolean colorize) { - return setPlaceholders(player, text); - } + /** + * Check if a String contains any PlaceholderAPI bracket placeholders ({@literal + * {_}}). + * + * @param text String to check + * @return true if String contains any matches to the bracket placeholder pattern, false otherwise + */ + public static boolean containsBracketPlaceholders(String text) { + return text != null && BRACKET_PLACEHOLDER_PATTERN.matcher(text).find(); + } - /** - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. - * - * @param player The offline player to parse the placeholders against - * @param text The text to parse - * @param pattern The Pattern to use - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setPlaceholders(OfflinePlayer player, String text, Pattern pattern) { - return setPlaceholders(player, text); - } + // === Deprecated API === - /** - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, List)} instead. - * - * @param player The offline player to parse the placeholders against - * @param text The List of text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setBracketPlaceholders(OfflinePlayer player, List text, - boolean colorize) { - return setBracketPlaceholders(player, text); - } + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static boolean registerExpansion(PlaceholderExpansion expansion) + { + return expansion.register(); + } - /** - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. - * - * @param player The offline player to parse the placeholders against - * @param text The text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setBracketPlaceholders(OfflinePlayer player, String text, boolean colorize) { - return setBracketPlaceholders(player, text); - } + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static boolean unregisterExpansion(PlaceholderExpansion expansion) + { + return expansion.unregister(); + } - /** - * @deprecated Will be removed in a future release. - * - * @param player The offline player to parse the placeholders against - * @param text The text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setBracketPlaceholders(Player player, String text, boolean colorize) { - return setBracketPlaceholders(player, text); - } + /** + * Get map of registered placeholders + * + * @deprecated Use {@link LocalExpansionManager#getExpansions()} instead. + * + * @return Map of registered placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static Map getPlaceholders() { + return PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() + .getExpansions().stream() + .collect(Collectors.toMap(PlaceholderExpansion::getIdentifier, ex -> ex)); + } - /** - * @deprecated Will be removed in a future release. - * - * @param player The offline player to parse the placeholders against - * @param text The List of text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setBracketPlaceholders(Player player, List text, - boolean colorize) { - return setBracketPlaceholders(player, text); - } + /** + * @deprecated Please use {@link PlaceholderExpansion} to + * register placeholders instead + * + * @param plugin The Plugin to register with this {@link PlaceholderHook} + * @param placeholderHook The {@link PlaceholderHook} to register + * @return always false + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static boolean registerPlaceholderHook(Plugin plugin, PlaceholderHook placeholderHook) { + Msg.warn("Nag author(s) %s of plugin %s about their usage of the deprecated PlaceholderHook" + + " class! This class will be removed in v2.13.0!", plugin.getDescription().getAuthors(), + plugin.getName()); + return false; + } - /** - * set relational placeholders in the text specified placeholders are matched with the pattern - * {@literal %%} when set with this method - * - * @param one Player to compare - * @param two Player to compare - * @param text Text to parse the placeholders in - * @param colorize If color codes ({@literal &[0-1a-fk-o]}) should be translated - * @return The text containing the parsed relational placeholders - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setRelationalPlaceholders(Player one, Player two, String text, - boolean colorize) { - return setRelationalPlaceholders(one, two, text); - } + /** + * @deprecated Please use {@link PlaceholderExpansion} to + * register placeholders instead + * + * @param identifier The identifier to use for the {@link PlaceholderHook} + * @param placeholderHook The {@link PlaceholderHook} to register + * @return always false + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static boolean registerPlaceholderHook(String identifier, + PlaceholderHook placeholderHook) { + Msg.warn("%s is attempting to register placeholders via deprecated PlaceholderHook class." + + " This class is no longer supported and will be removed in v2.13.0!", identifier); + return false; + } - /** - * Translate placeholders in the provided list based on the relation of the two provided players. - *
The pattern of a valid placeholder is {@literal %rel__%}. - * - * @param one First player to compare - * @param two Second player to compare - * @param text Text to parse the placeholders in - * @param colorize If color codes ({@literal &[0-1a-fk-o]}) should be translated - * @return The text containing the parsed relational placeholders - * @deprecated Use {@link #setRelationalPlaceholders(Player, Player, List)} instead. - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setRelationalPlaceholders(Player one, Player two, List text, - boolean colorize) { - return setRelationalPlaceholders(one, two, text); - } + /** + * @deprecated Please use {@link PlaceholderExpansion} to + * unregister placeholders instead + * + * @param plugin The plugin to unregister + * @return always false + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static boolean unregisterPlaceholderHook(Plugin plugin) { + Msg.warn("Nag author(s) %s of plugin %s about their usage of the PlaceholderAPI class." + + " This way of unregistering placeholders is no longer supported and will be removed" + + " in v2.13.0!", plugin.getDescription().getAuthors(), plugin.getName()); + return false; + } + + /** + * @deprecated Please use {@link PlaceholderExpansion} to + * unregister placeholders instead + * + * @param identifier The identifier to unregister + * @return always false + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static boolean unregisterPlaceholderHook(String identifier) { + Msg.warn("%s is attempting to unregister placeholders via PlaceholderAPI class." + + " This way of unregistering placeholders is no longer supported and will be removed" + + " in v2.13.0!", identifier); + return false; + } + + /** + * @deprecated Will be removed in a future release. + * + * @return Set of registered identifiers + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static Set getRegisteredPlaceholderPlugins() { + return getRegisteredIdentifiers(); + } + + /** + * @deprecated Will be removed in a future release. + * + * @return always null + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static Set getExternalPlaceholderPlugins() { + return null; + } + + /** + * @deprecated Please use {@link #setPlaceholders(OfflinePlayer, String)} instead + * + * @param player The offline player to parse the placeholders against + * @param text The text to parse + * @param pattern The Pattern to use + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setPlaceholders(OfflinePlayer player, + String text, Pattern pattern, boolean colorize) { + return setPlaceholders(player, text); + } + + /** + * @deprecated Please use {@link #setPlaceholders(OfflinePlayer, List)} instead + * + * @param player The offline player to parse the placeholders against + * @param text The List of text to parse + * @param pattern The Pattern to use + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setPlaceholders(OfflinePlayer player, + List text, Pattern pattern, boolean colorize) { + return setPlaceholders(player, text); + } + + /** + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, List)} instead. + * + * @param player The offline player to parse the placeholders against + * @param text The List of text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setPlaceholders(OfflinePlayer player, List text, + boolean colorize) { + return setPlaceholders(player, text); + } + + /** + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, List)} instead. + * + * @param player The offline player to parse the placeholders against + * @param text The List of text to parse + * @param pattern The Pattern to use + * @return String with the parsed placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setPlaceholders(OfflinePlayer player, List text, + Pattern pattern) { + return setPlaceholders(player, text); + } + /** + * @deprecated Will be removed in a future release. + * + * @param player The offline player to parse the placeholders against + * @param text The text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setPlaceholders(Player player, String text, boolean colorize) { + return setPlaceholders(player, text); + } + + /** + * @deprecated Will be removed in a future release. + * + * @param player The offline player to parse the placeholders against + * @param text The List of text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setPlaceholders(Player player, List text, boolean colorize) { + return setPlaceholders(player, text); + } + + /** + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. + * + * @param player The offline player to parse the placeholders against + * @param text The text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setPlaceholders(OfflinePlayer player, String text, boolean colorize) { + return setPlaceholders(player, text); + } + + /** + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. + * + * @param player The offline player to parse the placeholders against + * @param text The text to parse + * @param pattern The Pattern to use + * @return String with the parsed placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setPlaceholders(OfflinePlayer player, String text, Pattern pattern) { + return setPlaceholders(player, text); + } + + /** + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, List)} instead. + * + * @param player The offline player to parse the placeholders against + * @param text The List of text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setBracketPlaceholders(OfflinePlayer player, List text, + boolean colorize) { + return setBracketPlaceholders(player, text); + } + + /** + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. + * + * @param player The offline player to parse the placeholders against + * @param text The text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setBracketPlaceholders(OfflinePlayer player, String text, boolean colorize) { + return setBracketPlaceholders(player, text); + } + + /** + * @deprecated Will be removed in a future release. + * + * @param player The offline player to parse the placeholders against + * @param text The text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setBracketPlaceholders(Player player, String text, boolean colorize) { + return setBracketPlaceholders(player, text); + } + + /** + * @deprecated Will be removed in a future release. + * + * @param player The offline player to parse the placeholders against + * @param text The List of text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setBracketPlaceholders(Player player, List text, + boolean colorize) { + return setBracketPlaceholders(player, text); + } + + /** + * set relational placeholders in the text specified placeholders are matched with the pattern + * {@literal %%} when set with this method + * + * @param one Player to compare + * @param two Player to compare + * @param text Text to parse the placeholders in + * @param colorize If color codes ({@literal &[0-1a-fk-o]}) should be translated + * @return The text containing the parsed relational placeholders + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setRelationalPlaceholders(Player one, Player two, String text, + boolean colorize) { + return setRelationalPlaceholders(one, two, text); + } + + /** + * Translate placeholders in the provided list based on the relation of the two provided players. + *
The pattern of a valid placeholder is {@literal %rel__%}. + * + * @param one First player to compare + * @param two Second player to compare + * @param text Text to parse the placeholders in + * @param colorize If color codes ({@literal &[0-1a-fk-o]}) should be translated + * @return The text containing the parsed relational placeholders + * @deprecated Use {@link #setRelationalPlaceholders(Player, Player, List)} instead. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setRelationalPlaceholders(Player one, Player two, List text, + boolean colorize) { + return setRelationalPlaceholders(one, two, text); + } } diff --git a/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java b/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java index c374aa2..f6eaaf7 100644 --- a/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java +++ b/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java @@ -25,6 +25,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; import me.clip.placeholderapi.commands.PlaceholderCommandRouter; +import me.clip.placeholderapi.commands.TestCommand; import me.clip.placeholderapi.configuration.PlaceholderAPIConfig; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import me.clip.placeholderapi.expansion.Version; @@ -53,228 +54,229 @@ import org.jetbrains.annotations.NotNull; */ public final class PlaceholderAPIPlugin extends JavaPlugin { - @NotNull - private static final Version VERSION; - private static PlaceholderAPIPlugin instance; + @NotNull + private static final Version VERSION; + private static PlaceholderAPIPlugin instance; - static { - String version = Bukkit.getServer().getBukkitVersion().split("-")[0]; - String suffix; - if (version.chars() - .filter(c -> c == '.') - .count() == 1) { - suffix = "R1"; - version = 'v' + version.replace('.', '_') + '_' + suffix; - } else { - int minor = Integer.parseInt(version.split("\\.")[2].charAt(0) + ""); - version = 'v' + version.replace('.', '_').replace("_" + minor, "") + '_' + "R" + (minor - 1); + static { + String version = Bukkit.getServer().getBukkitVersion().split("-")[0]; + String suffix; + if (version.chars() + .filter(c -> c == '.') + .count() == 1) { + suffix = "R1"; + version = 'v' + version.replace('.', '_') + '_' + suffix; + } else { + int minor = Integer.parseInt(version.split("\\.")[2].charAt(0) + ""); + version = 'v' + version.replace('.', '_').replace("_" + minor, "") + '_' + "R" + (minor - 1); + } + + boolean isSpigot; + try { + Class.forName("org.spigotmc.SpigotConfig"); + isSpigot = true; + } catch (final ExceptionInInitializerError | ClassNotFoundException ignored) { + isSpigot = false; + } + + VERSION = new Version(version, isSpigot); } - boolean isSpigot; - try { - Class.forName("org.spigotmc.SpigotConfig"); - isSpigot = true; - } catch (final ExceptionInInitializerError | ClassNotFoundException ignored) { - isSpigot = false; + @NotNull + private final PlaceholderAPIConfig config = new PlaceholderAPIConfig(this); + + @NotNull + private final LocalExpansionManager localExpansionManager = new LocalExpansionManager(this); + @NotNull + private final CloudExpansionManager cloudExpansionManager = new CloudExpansionManager(this); + @NotNull + private final TaskScheduler scheduler = UniversalScheduler.getScheduler(this); + + private BukkitAudiences adventure; + + + /** + * Gets the static instance of the main class for PlaceholderAPI. This class is not the actual API + * class, this is the main class that extends JavaPlugin. For most API methods, use static methods + * available from the class: {@link PlaceholderAPI} + * + * @return PlaceholderAPIPlugin instance + */ + @NotNull + public static PlaceholderAPIPlugin getInstance() { + return instance; } - VERSION = new Version(version, isSpigot); - } - - @NotNull - private final PlaceholderAPIConfig config = new PlaceholderAPIConfig(this); - - @NotNull - private final LocalExpansionManager localExpansionManager = new LocalExpansionManager(this); - @NotNull - private final CloudExpansionManager cloudExpansionManager = new CloudExpansionManager(this); - @NotNull - private final TaskScheduler scheduler = UniversalScheduler.getScheduler(this); - - private BukkitAudiences adventure; - - - /** - * Gets the static instance of the main class for PlaceholderAPI. This class is not the actual API - * class, this is the main class that extends JavaPlugin. For most API methods, use static methods - * available from the class: {@link PlaceholderAPI} - * - * @return PlaceholderAPIPlugin instance - */ - @NotNull - public static PlaceholderAPIPlugin getInstance() { - return instance; - } - - /** - * Get the configurable {@linkplain String} value that should be returned when a boolean is true - * - * @return string value of true - */ - @NotNull - public static String booleanTrue() { - return getInstance().getPlaceholderAPIConfig().booleanTrue(); - } - - /** - * Get the configurable {@linkplain String} value that should be returned when a boolean is false - * - * @return string value of false - */ - @NotNull - public static String booleanFalse() { - return getInstance().getPlaceholderAPIConfig().booleanFalse(); - } - - /** - * Get the configurable {@linkplain SimpleDateFormat} object that is used to parse time for - * generic time based placeholders - * - * @return date format - */ - @NotNull - public static SimpleDateFormat getDateFormat() { - try { - return new SimpleDateFormat(getInstance().getPlaceholderAPIConfig().dateFormat()); - } catch (final IllegalArgumentException ex) { - Msg.warn("Configured date format ('%s') is invalid! Defaulting to 'MM/dd/yy HH:mm:ss'", - ex, getInstance().getPlaceholderAPIConfig().dateFormat()); - return new SimpleDateFormat("MM/dd/yy HH:mm:ss"); - } - } - - @Deprecated - public static Version getServerVersion() { - return VERSION; - } - - @Override - public void onLoad() { - instance = this; - - saveDefaultConfig(); - } - - @Override - public void onEnable() { - setupCommand(); - setupMetrics(); - setupExpansions(); - - adventure = BukkitAudiences.create(this); - - if (config.isCloudEnabled()) { - getCloudExpansionManager().load(); + /** + * Get the configurable {@linkplain String} value that should be returned when a boolean is true + * + * @return string value of true + */ + @NotNull + public static String booleanTrue() { + return getInstance().getPlaceholderAPIConfig().booleanTrue(); } - if (config.checkUpdates()) { - new UpdateChecker(this).fetch(); - } - } - - @Override - public void onDisable() { - getCloudExpansionManager().kill(); - getLocalExpansionManager().kill(); - - HandlerList.unregisterAll(this); - - scheduler.cancelTasks(this); - - adventure.close(); - adventure = null; - - instance = null; - } - - public void reloadConf(@NotNull final CommandSender sender) { - getLocalExpansionManager().kill(); - - reloadConfig(); - - getLocalExpansionManager().load(sender); - - if (config.isCloudEnabled()) { - getCloudExpansionManager().load(); - } else { - getCloudExpansionManager().kill(); - } - } - - @NotNull - public LocalExpansionManager getLocalExpansionManager() { - return localExpansionManager; - } - - @NotNull - public CloudExpansionManager getCloudExpansionManager() { - return cloudExpansionManager; - } - - @NotNull - public BukkitAudiences getAdventure() { - if(adventure == null) { - throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!"); + /** + * Get the configurable {@linkplain String} value that should be returned when a boolean is false + * + * @return string value of false + */ + @NotNull + public static String booleanFalse() { + return getInstance().getPlaceholderAPIConfig().booleanFalse(); } - return adventure; - } - - @NotNull - public TaskScheduler getScheduler() { - return scheduler; - } - - /** - * Obtain the configuration class for PlaceholderAPI. - * - * @return PlaceholderAPIConfig instance - */ - @NotNull - public PlaceholderAPIConfig getPlaceholderAPIConfig() { - return config; - } - - private void setupCommand() { - final PluginCommand pluginCommand = getCommand("placeholderapi"); - if (pluginCommand == null) { - return; + /** + * Get the configurable {@linkplain SimpleDateFormat} object that is used to parse time for + * generic time based placeholders + * + * @return date format + */ + @NotNull + public static SimpleDateFormat getDateFormat() { + try { + return new SimpleDateFormat(getInstance().getPlaceholderAPIConfig().dateFormat()); + } catch (final IllegalArgumentException ex) { + Msg.warn("Configured date format ('%s') is invalid! Defaulting to 'MM/dd/yy HH:mm:ss'", + ex, getInstance().getPlaceholderAPIConfig().dateFormat()); + return new SimpleDateFormat("MM/dd/yy HH:mm:ss"); + } } - final PlaceholderCommandRouter router = new PlaceholderCommandRouter(this); - pluginCommand.setExecutor(router); - pluginCommand.setTabCompleter(router); - } - - private void setupMetrics() { - final Metrics metrics = new Metrics(this, 438); - metrics.addCustomChart(new SimplePie("using_expansion_cloud", - () -> getPlaceholderAPIConfig().isCloudEnabled() ? "yes" : "no")); - - metrics.addCustomChart(new SimplePie("using_spigot", () -> getServerVersion().isSpigot() ? "yes" : "no")); - - metrics.addCustomChart(new AdvancedPie("expansions_used", () -> { - final Map values = new HashMap<>(); - - for (final PlaceholderExpansion expansion : getLocalExpansionManager().getExpansions()) { - values.put(expansion.getRequiredPlugin() == null ? expansion.getIdentifier() - : expansion.getRequiredPlugin(), 1); - } - - return values; - })); - } - - private void setupExpansions() { - Bukkit.getPluginManager().registerEvents(getLocalExpansionManager(), this); - - try { - Class.forName("org.bukkit.event.server.ServerLoadEvent"); - new ServerLoadEventListener(this); - } catch (final ClassNotFoundException ignored) { - scheduler - .runTaskLater(() -> getLocalExpansionManager().load(Bukkit.getConsoleSender()), 1); + @Deprecated + public static Version getServerVersion() { + return VERSION; + } + + @Override + public void onLoad() { + instance = this; + + saveDefaultConfig(); + } + + @Override + public void onEnable() { + registerCommand("test", new TestCommand()); + setupCommand(); + setupMetrics(); + setupExpansions(); + + adventure = BukkitAudiences.create(this); + + if (config.isCloudEnabled()) { + getCloudExpansionManager().load(); + } + + if (config.checkUpdates()) { + new UpdateChecker(this).fetch(); + } + } + + @Override + public void onDisable() { + getCloudExpansionManager().kill(); + getLocalExpansionManager().kill(); + + HandlerList.unregisterAll(this); + + scheduler.cancelTasks(this); + + adventure.close(); + adventure = null; + + instance = null; + } + + public void reloadConf(@NotNull final CommandSender sender) { + getLocalExpansionManager().kill(); + + reloadConfig(); + + getLocalExpansionManager().load(sender); + + if (config.isCloudEnabled()) { + getCloudExpansionManager().load(); + } else { + getCloudExpansionManager().kill(); + } + } + + @NotNull + public LocalExpansionManager getLocalExpansionManager() { + return localExpansionManager; + } + + @NotNull + public CloudExpansionManager getCloudExpansionManager() { + return cloudExpansionManager; + } + + @NotNull + public BukkitAudiences getAdventure() { + if(adventure == null) { + throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!"); + } + + return adventure; + } + + @NotNull + public TaskScheduler getScheduler() { + return scheduler; + } + + /** + * Obtain the configuration class for PlaceholderAPI. + * + * @return PlaceholderAPIConfig instance + */ + @NotNull + public PlaceholderAPIConfig getPlaceholderAPIConfig() { + return config; + } + + private void setupCommand() { + final PluginCommand pluginCommand = getCommand("placeholderapi"); + if (pluginCommand == null) { + return; + } + + final PlaceholderCommandRouter router = new PlaceholderCommandRouter(this); + pluginCommand.setExecutor(router); + pluginCommand.setTabCompleter(router); + } + + private void setupMetrics() { + final Metrics metrics = new Metrics(this, 438); + metrics.addCustomChart(new SimplePie("using_expansion_cloud", + () -> getPlaceholderAPIConfig().isCloudEnabled() ? "yes" : "no")); + + metrics.addCustomChart(new SimplePie("using_spigot", () -> getServerVersion().isSpigot() ? "yes" : "no")); + + metrics.addCustomChart(new AdvancedPie("expansions_used", () -> { + final Map values = new HashMap<>(); + + for (final PlaceholderExpansion expansion : getLocalExpansionManager().getExpansions()) { + values.put(expansion.getRequiredPlugin() == null ? expansion.getIdentifier() + : expansion.getRequiredPlugin(), 1); + } + + return values; + })); + } + + private void setupExpansions() { + Bukkit.getPluginManager().registerEvents(getLocalExpansionManager(), this); + + try { + Class.forName("org.bukkit.event.server.ServerLoadEvent"); + new ServerLoadEventListener(this); + } catch (final ClassNotFoundException ignored) { + scheduler + .runTaskLater(() -> getLocalExpansionManager().load(Bukkit.getConsoleSender()), 1); + } } - } } diff --git a/src/main/java/me/clip/placeholderapi/PlaceholderHook.java b/src/main/java/me/clip/placeholderapi/PlaceholderHook.java index 255a27c..0625656 100644 --- a/src/main/java/me/clip/placeholderapi/PlaceholderHook.java +++ b/src/main/java/me/clip/placeholderapi/PlaceholderHook.java @@ -29,7 +29,6 @@ import org.jetbrains.annotations.Nullable; import java.util.Optional; public abstract class PlaceholderHook { - @Deprecated @Nullable public String onRequest(final OfflinePlayer player, @NotNull final String params) { if (player != null && player.isOnline()) { @@ -39,16 +38,8 @@ public abstract class PlaceholderHook { return onPlaceholderRequest(null, params); } - @Deprecated @Nullable public String onPlaceholderRequest(final Player player, @NotNull final String params) { return null; } - - @Nullable - public Component onPlaceholderComponentRequest(final OfflinePlayer player, @NotNull final String params) { - final String result = onRequest(player, params); - - return result == null ? null : Component.text(result); - } } diff --git a/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java b/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java index 8136168..ae94bc2 100644 --- a/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java +++ b/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java @@ -22,10 +22,12 @@ package me.clip.placeholderapi.commands; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; + import java.util.List; import java.util.Locale; import java.util.Set; import java.util.stream.Stream; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; @@ -34,75 +36,75 @@ import org.jetbrains.annotations.Unmodifiable; public abstract class PlaceholderCommand { - @NotNull - private final String label; - @NotNull - private final Set alias; + @NotNull + private final String label; + @NotNull + private final Set alias; - @Nullable - private String permission; + @Nullable + private String permission; - protected PlaceholderCommand(@NotNull final String label, @NotNull final String... alias) { - this.label = label; - this.alias = Sets.newHashSet(alias); + protected PlaceholderCommand(@NotNull final String label, @NotNull final String... alias) { + this.label = label; + this.alias = Sets.newHashSet(alias); - setPermission("placeholderapi." + label); - } - - @NotNull - public static Stream filterByPermission(@NotNull final CommandSender sender, - @NotNull final Stream commands) { - return commands.filter( - target -> target.getPermission() == null || sender.hasPermission(target.getPermission())); - } - - public static void suggestByParameter(@NotNull final Stream possible, - @NotNull final List suggestions, @Nullable final String parameter) { - if (parameter == null) { - possible.forEach(suggestions::add); - } else { - possible.filter(suggestion -> suggestion.toLowerCase(Locale.ROOT).startsWith(parameter.toLowerCase(Locale.ROOT))) - .forEach(suggestions::add); + setPermission("placeholderapi." + label); } - } - @NotNull - public final String getLabel() { - return label; - } + @NotNull + public static Stream filterByPermission(@NotNull final CommandSender sender, + @NotNull final Stream commands) { + return commands.filter( + target -> target.getPermission() == null || sender.hasPermission(target.getPermission())); + } - @NotNull - @Unmodifiable - public final Set getAlias() { - return ImmutableSet.copyOf(alias); - } + public static void suggestByParameter(@NotNull final Stream possible, + @NotNull final List suggestions, @Nullable final String parameter) { + if (parameter == null) { + possible.forEach(suggestions::add); + } else { + possible.filter(suggestion -> suggestion.toLowerCase(Locale.ROOT).startsWith(parameter.toLowerCase(Locale.ROOT))) + .forEach(suggestions::add); + } + } - @NotNull - @Unmodifiable - public final Set getLabels() { - return ImmutableSet.builder().add(label).addAll(alias).build(); - } + @NotNull + public final String getLabel() { + return label; + } - @Nullable - public final String getPermission() { - return permission; - } + @NotNull + @Unmodifiable + public final Set getAlias() { + return ImmutableSet.copyOf(alias); + } - public void setPermission(@NotNull final String permission) { - this.permission = permission; - } + @NotNull + @Unmodifiable + public final Set getLabels() { + return ImmutableSet.builder().add(label).addAll(alias).build(); + } - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { + @Nullable + public final String getPermission() { + return permission; + } - } + public void setPermission(@NotNull final String permission) { + this.permission = permission; + } - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { - } + } + + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + + } } diff --git a/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java b/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java index 7ea3f42..d53f4ce 100644 --- a/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java +++ b/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java @@ -22,6 +22,7 @@ package me.clip.placeholderapi.commands; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -30,6 +31,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Stream; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.impl.cloud.CommandECloud; import me.clip.placeholderapi.commands.impl.local.CommandDump; @@ -51,93 +53,93 @@ import org.jetbrains.annotations.Unmodifiable; public final class PlaceholderCommandRouter implements CommandExecutor, TabCompleter { - @Unmodifiable - private static final List COMMANDS = ImmutableList.of(new CommandHelp(), - new CommandInfo(), - new CommandList(), - new CommandDump(), - new CommandECloud(), - new CommandParse(), - new CommandReload(), - new CommandVersion(), - new CommandExpansionRegister(), - new CommandExpansionUnregister()); + @Unmodifiable + private static final List COMMANDS = ImmutableList.of(new CommandHelp(), + new CommandInfo(), + new CommandList(), + new CommandDump(), + new CommandECloud(), + new CommandParse(), + new CommandReload(), + new CommandVersion(), + new CommandExpansionRegister(), + new CommandExpansionUnregister()); - @NotNull - private final PlaceholderAPIPlugin plugin; - @NotNull - @Unmodifiable - private final Map commands; + @NotNull + private final PlaceholderAPIPlugin plugin; + @NotNull + @Unmodifiable + private final Map commands; - public PlaceholderCommandRouter(@NotNull final PlaceholderAPIPlugin plugin) { - this.plugin = plugin; + public PlaceholderCommandRouter(@NotNull final PlaceholderAPIPlugin plugin) { + this.plugin = plugin; - final ImmutableMap.Builder commands = ImmutableMap.builder(); + final ImmutableMap.Builder commands = ImmutableMap.builder(); - for (final PlaceholderCommand command : COMMANDS) { - command.getLabels().forEach(label -> commands.put(label, command)); + for (final PlaceholderCommand command : COMMANDS) { + command.getLabels().forEach(label -> commands.put(label, command)); + } + + this.commands = commands.build(); } - this.commands = commands.build(); - } + @Override + public boolean onCommand(@NotNull final CommandSender sender, @NotNull final Command command, + @NotNull final String alias, @NotNull final String[] args) { + if (args.length == 0) { + final PlaceholderCommand fallback = commands.get("version"); + if (fallback != null) { + fallback.evaluate(plugin, sender, "", Collections.emptyList()); + } - @Override - public boolean onCommand(@NotNull final CommandSender sender, @NotNull final Command command, - @NotNull final String alias, @NotNull final String[] args) { - if (args.length == 0) { - final PlaceholderCommand fallback = commands.get("version"); - if (fallback != null) { - fallback.evaluate(plugin, sender, "", Collections.emptyList()); - } + return true; + } - return true; + final String search = args[0].toLowerCase(Locale.ROOT); + final PlaceholderCommand target = commands.get(search); + + if (target == null) { + Msg.msg(sender, "&cUnknown command &7" + search); + return true; + } + + final String permission = target.getPermission(); + if (permission != null && !permission.isEmpty() && !sender.hasPermission(permission)) { + Msg.msg(sender, "&cYou do not have permission to do this!"); + return true; + } + + target + .evaluate(plugin, sender, search, Arrays.asList(Arrays.copyOfRange(args, 1, args.length))); + + return true; } - final String search = args[0].toLowerCase(Locale.ROOT); - final PlaceholderCommand target = commands.get(search); + @Override + public List onTabComplete(@NotNull final CommandSender sender, + @NotNull final Command command, @NotNull final String alias, @NotNull final String[] args) { + final List suggestions = new ArrayList<>(); - if (target == null) { - Msg.msg(sender, "&cUnknown command &7" + search); - return true; + if (args.length > 1) { + final PlaceholderCommand target = this.commands.get(args[0].toLowerCase(Locale.ROOT)); + + if (target != null) { + target.complete(plugin, sender, args[0].toLowerCase(Locale.ROOT), + Arrays.asList(Arrays.copyOfRange(args, 1, args.length)), suggestions); + } + + return suggestions; + } + + final Stream targets = PlaceholderCommand + .filterByPermission(sender, commands.values().stream()).map(PlaceholderCommand::getLabels) + .flatMap(Collection::stream); + PlaceholderCommand.suggestByParameter(targets, suggestions, args.length == 0 ? null : args[0]); + + return suggestions; } - final String permission = target.getPermission(); - if (permission != null && !permission.isEmpty() && !sender.hasPermission(permission)) { - Msg.msg(sender, "&cYou do not have permission to do this!"); - return true; - } - - target - .evaluate(plugin, sender, search, Arrays.asList(Arrays.copyOfRange(args, 1, args.length))); - - return true; - } - - @Override - public List onTabComplete(@NotNull final CommandSender sender, - @NotNull final Command command, @NotNull final String alias, @NotNull final String[] args) { - final List suggestions = new ArrayList<>(); - - if (args.length > 1) { - final PlaceholderCommand target = this.commands.get(args[0].toLowerCase(Locale.ROOT)); - - if (target != null) { - target.complete(plugin, sender, args[0].toLowerCase(Locale.ROOT), - Arrays.asList(Arrays.copyOfRange(args, 1, args.length)), suggestions); - } - - return suggestions; - } - - final Stream targets = PlaceholderCommand - .filterByPermission(sender, commands.values().stream()).map(PlaceholderCommand::getLabels) - .flatMap(Collection::stream); - PlaceholderCommand.suggestByParameter(targets, suggestions, args.length == 0 ? null : args[0]); - - return suggestions; - } - } diff --git a/src/main/java/me/clip/placeholderapi/commands/TestCommand.java b/src/main/java/me/clip/placeholderapi/commands/TestCommand.java new file mode 100644 index 0000000..fe739e9 --- /dev/null +++ b/src/main/java/me/clip/placeholderapi/commands/TestCommand.java @@ -0,0 +1,51 @@ +package me.clip.placeholderapi.commands; + +import io.papermc.paper.command.brigadier.BasicCommand; +import io.papermc.paper.command.brigadier.CommandSourceStack; +import me.clip.placeholderapi.PAPIComponents; +import me.clip.placeholderapi.PlaceholderAPI; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.HoverEvent; +import net.kyori.adventure.text.event.HoverEventSource; +import net.kyori.adventure.text.format.TextColor; +import net.kyori.adventure.text.minimessage.MiniMessage; +import org.bukkit.OfflinePlayer; + +public class TestCommand implements BasicCommand { + private static final MiniMessage MINI = MiniMessage.miniMessage(); + + @Override + public void execute(final CommandSourceStack commandSourceStack, final String[] strings) { +// final Component component = Component.text("Woo! Test: %player_name%").color(TextColor.color(50, 168, 82)).hoverEvent(HoverEvent.showText(Component.text("OMG %player_gamemode%"))); + final Component component = Component.text("Woo! Test: %player_name%"); + + String ser = MINI.serialize(component); + System.out.println(ser); + + commandSourceStack.getSender().sendMessage( + PAPIComponents.setPlaceholders((OfflinePlayer) commandSourceStack.getSender(), component) + ); + + long tmp = System.currentTimeMillis(); + for (int i = 0; i < 100000; ++i) { + PAPIComponents.setPlaceholders((OfflinePlayer) commandSourceStack.getSender(), component); + } + commandSourceStack.getSender().sendMessage(String.valueOf(System.currentTimeMillis() - tmp)); + + tmp = System.currentTimeMillis(); + for (int i = 0; i < 100000; ++i) { + PlaceholderAPI.setPlaceholders((OfflinePlayer) commandSourceStack.getSender(), "Woo! Test: %player_name%"); + } + commandSourceStack.getSender().sendMessage(String.valueOf(System.currentTimeMillis() - tmp)); + + tmp = System.currentTimeMillis(); + for (int i = 0; i < 100000; ++i) { + final String serr = MINI.serialize(component); + final String repl = PlaceholderAPI.setPlaceholders((OfflinePlayer) commandSourceStack.getSender(), serr); + MINI.deserialize(repl); + } + commandSourceStack.getSender().sendMessage(String.valueOf(System.currentTimeMillis() - tmp)); + + + } +} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloud.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloud.java index 4d03de1..f9c2e3e 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloud.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloud.java @@ -37,110 +37,110 @@ import java.util.stream.Stream; public final class CommandECloud extends PlaceholderCommand { - @Unmodifiable - private static final List COMMANDS = ImmutableList - .of(new CommandECloudClear(), - new CommandECloudStatus(), - new CommandECloudUpdate(), - new CommandECloudRefresh(), - new CommandECloudDownload(), - new CommandECloudExpansionInfo(), - new CommandECloudExpansionList(), - new CommandECloudExpansionPlaceholders()); + @Unmodifiable + private static final List COMMANDS = ImmutableList + .of(new CommandECloudClear(), + new CommandECloudStatus(), + new CommandECloudUpdate(), + new CommandECloudRefresh(), + new CommandECloudDownload(), + new CommandECloudExpansionInfo(), + new CommandECloudExpansionList(), + new CommandECloudExpansionPlaceholders()); - static { - COMMANDS - .forEach(command -> command.setPermission("placeholderapi.ecloud." + command.getLabel())); - } - - @NotNull - @Unmodifiable - private final Map commands; - - - public CommandECloud() { - super("ecloud"); - - final ImmutableMap.Builder commands = ImmutableMap.builder(); - - for (final PlaceholderCommand command : COMMANDS) { - command.getLabels().forEach(label -> commands.put(label, command)); + static { + COMMANDS + .forEach(command -> command.setPermission("placeholderapi.ecloud." + command.getLabel())); } - this.commands = commands.build(); - } + @NotNull + @Unmodifiable + private final Map commands; - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&b&lPlaceholderAPI &8- &7eCloud Help Menu &8- ", - " ", - "&b/papi &fecloud status", - " &7&oView status of the eCloud", - "&b/papi &fecloud list {page}", - " &7&oList all/author specific available expansions", - "&b/papi &fecloud info {version}", - " &7&oView information about a specific expansion available on the eCloud", - "&b/papi &fecloud placeholders ", - " &7&oView placeholders for an expansion", - "&b/papi &fecloud download {version}", - " &7&oDownload an expansion from the eCloud", - "&b/papi &fecloud update ", - " &7&oUpdate a specific/all installed expansions", - "&b/papi &fecloud refresh", - " &7&oFetch the most up to date list of expansions available.", - "&b/papi &fecloud clear", - " &7&oClear the expansion cloud cache."); + public CommandECloud() { + super("ecloud"); - return; + final ImmutableMap.Builder commands = ImmutableMap.builder(); + + for (final PlaceholderCommand command : COMMANDS) { + command.getLabels().forEach(label -> commands.put(label, command)); + } + + this.commands = commands.build(); } - final String search = params.get(0).toLowerCase(Locale.ROOT); - final PlaceholderCommand target = commands.get(search); - if (target == null) { - Msg.msg(sender, "&cUnknown command &7ecloud " + search); - return; + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&b&lPlaceholderAPI &8- &7eCloud Help Menu &8- ", + " ", + "&b/papi &fecloud status", + " &7&oView status of the eCloud", + "&b/papi &fecloud list {page}", + " &7&oList all/author specific available expansions", + "&b/papi &fecloud info {version}", + " &7&oView information about a specific expansion available on the eCloud", + "&b/papi &fecloud placeholders ", + " &7&oView placeholders for an expansion", + "&b/papi &fecloud download {version}", + " &7&oDownload an expansion from the eCloud", + "&b/papi &fecloud update ", + " &7&oUpdate a specific/all installed expansions", + "&b/papi &fecloud refresh", + " &7&oFetch the most up to date list of expansions available.", + "&b/papi &fecloud clear", + " &7&oClear the expansion cloud cache."); + + return; + } + + final String search = params.get(0).toLowerCase(Locale.ROOT); + final PlaceholderCommand target = commands.get(search); + + if (target == null) { + Msg.msg(sender, "&cUnknown command &7ecloud " + search); + return; + } + + final String permission = target.getPermission(); + if (permission != null && !permission.isEmpty() && !sender.hasPermission(permission)) { + Msg.msg(sender, "&cYou do not have permission to do this!"); + return; + } + + if (!plugin.getPlaceholderAPIConfig().isCloudEnabled()) { + Msg.msg(sender, "&cThe eCloud Manager is not enabled! To enable it, set 'cloud_enabled' to true and reload the plugin."); + return; + } + + target.evaluate(plugin, sender, search, params.subList(1, params.size())); } - final String permission = target.getPermission(); - if (permission != null && !permission.isEmpty() && !sender.hasPermission(permission)) { - Msg.msg(sender, "&cYou do not have permission to do this!"); - return; + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() <= 1) { + final Stream targets = filterByPermission(sender, commands.values().stream()) + .map(PlaceholderCommand::getLabels).flatMap(Collection::stream); + suggestByParameter(targets, suggestions, params.isEmpty() ? null : params.get(0)); + + return; // send sub commands + } + + final String search = params.get(0).toLowerCase(Locale.ROOT); + final PlaceholderCommand target = commands.get(search); + + if (target == null) { + return; + } + + target.complete(plugin, sender, search, params.subList(1, params.size()), suggestions); } - if (!plugin.getPlaceholderAPIConfig().isCloudEnabled()) { - Msg.msg(sender, "&cThe eCloud Manager is not enabled! To enable it, set 'cloud_enabled' to true and reload the plugin."); - return; - } - - target.evaluate(plugin, sender, search, params.subList(1, params.size())); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() <= 1) { - final Stream targets = filterByPermission(sender, commands.values().stream()) - .map(PlaceholderCommand::getLabels).flatMap(Collection::stream); - suggestByParameter(targets, suggestions, params.isEmpty() ? null : params.get(0)); - - return; // send sub commands - } - - final String search = params.get(0).toLowerCase(Locale.ROOT); - final PlaceholderCommand target = commands.get(search); - - if (target == null) { - return; - } - - target.complete(plugin, sender, search, params.subList(1, params.size()), suggestions); - } - } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudClear.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudClear.java index 6083d5d..db0b145 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudClear.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudClear.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.commands.impl.cloud; import java.util.List; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.util.Msg; @@ -30,17 +31,17 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandECloudClear extends PlaceholderCommand { - public CommandECloudClear() { - super("clear"); - } + public CommandECloudClear() { + super("clear"); + } - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - plugin.getCloudExpansionManager().clean(); - Msg.msg(sender, - "&aThe eCloud cache has been cleared!"); - } + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + plugin.getCloudExpansionManager().clean(); + Msg.msg(sender, + "&aThe eCloud cache has been cleared!"); + } } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudDownload.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudDownload.java index 1085eb8..755c46a 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudDownload.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudDownload.java @@ -24,6 +24,7 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Stream; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.expansion.cloud.CloudExpansion; @@ -34,106 +35,106 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandECloudDownload extends PlaceholderCommand { - public CommandECloudDownload() { - super("download"); - } - - private boolean isBlockedExpansion(String name) { - String env = System.getenv("PAPI_BLOCKED_EXPANSIONS"); - if (env == null) { - return false; + public CommandECloudDownload() { + super("download"); } - return Arrays.stream(env.split(",")) - .anyMatch(s -> s.equalsIgnoreCase(name)); - } + private boolean isBlockedExpansion(String name) { + String env = System.getenv("PAPI_BLOCKED_EXPANSIONS"); + if (env == null) { + return false; + } - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must supply the name of an expansion."); - return; + return Arrays.stream(env.split(",")) + .anyMatch(s -> s.equalsIgnoreCase(name)); } - if (isBlockedExpansion(params.get(0))) { - Msg.msg(sender, - "&cThis expansion can't be downloaded."); - return; - } - - final CloudExpansion expansion = plugin.getCloudExpansionManager() - .findCloudExpansionByName(params.get(0)).orElse(null); - if (expansion == null) { - Msg.msg(sender, - "&cFailed to find an expansion named: &f" + params.get(0)); - return; - } - - if (!expansion.isVerified()) { - Msg.msg(sender, "&cThe expansion '&f" + params.get(0) + "&c' is not verified and can only be downloaded manually from &fhttps://placeholderapi.com/ecloud"); - return; - } - - final CloudExpansion.Version version; - if (params.size() < 2) { - version = expansion.getVersion(expansion.getLatestVersion()); - if (version == null) { - Msg.msg(sender, - "&cCould not find latest version for expansion."); - return; - } - } else { - version = expansion.getVersion(params.get(1)); - if (version == null) { - Msg.msg(sender, - "&cCould not find specified version: &f" + params.get(1), - "&7Available versions: &f" + expansion.getAvailableVersions()); - return; - } - } - - plugin.getCloudExpansionManager().downloadExpansion(expansion, version) - .whenComplete((file, exception) -> { - if (exception != null) { + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { Msg.msg(sender, - "&cFailed to download expansion: &f" + exception.getMessage()); + "&cYou must supply the name of an expansion."); return; - } + } - Msg.msg(sender, - "&aSuccessfully downloaded expansion &f" + expansion.getName() + " [" + version - .getVersion() + "] &ato file: &f" + file.getName(), - "&aMake sure to type &f/papi reload &ato enable your new expansion!"); + if (isBlockedExpansion(params.get(0))) { + Msg.msg(sender, + "&cThis expansion can't be downloaded."); + return; + } - plugin.getCloudExpansionManager().load(); - }); - } + final CloudExpansion expansion = plugin.getCloudExpansionManager() + .findCloudExpansionByName(params.get(0)).orElse(null); + if (expansion == null) { + Msg.msg(sender, + "&cFailed to find an expansion named: &f" + params.get(0)); + return; + } - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 2) { - return; + if (!expansion.isVerified()) { + Msg.msg(sender, "&cThe expansion '&f" + params.get(0) + "&c' is not verified and can only be downloaded manually from &fhttps://placeholderapi.com/ecloud"); + return; + } + + final CloudExpansion.Version version; + if (params.size() < 2) { + version = expansion.getVersion(expansion.getLatestVersion()); + if (version == null) { + Msg.msg(sender, + "&cCould not find latest version for expansion."); + return; + } + } else { + version = expansion.getVersion(params.get(1)); + if (version == null) { + Msg.msg(sender, + "&cCould not find specified version: &f" + params.get(1), + "&7Available versions: &f" + expansion.getAvailableVersions()); + return; + } + } + + plugin.getCloudExpansionManager().downloadExpansion(expansion, version) + .whenComplete((file, exception) -> { + if (exception != null) { + Msg.msg(sender, + "&cFailed to download expansion: &f" + exception.getMessage()); + return; + } + + Msg.msg(sender, + "&aSuccessfully downloaded expansion &f" + expansion.getName() + " [" + version + .getVersion() + "] &ato file: &f" + file.getName(), + "&aMake sure to type &f/papi reload &ato enable your new expansion!"); + + plugin.getCloudExpansionManager().load(); + }); } - if (params.size() <= 1) { - final Stream names = plugin.getCloudExpansionManager().getCloudExpansions().values() - .stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_')); - suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); - return; - } + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 2) { + return; + } - final Optional expansion = plugin.getCloudExpansionManager() - .findCloudExpansionByName(params.get(0)); - if (!expansion.isPresent()) { - return; - } + if (params.size() <= 1) { + final Stream names = plugin.getCloudExpansionManager().getCloudExpansions().values() + .stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_')); + suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); + return; + } - suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1)); - } + final Optional expansion = plugin.getCloudExpansionManager() + .findCloudExpansionByName(params.get(0)); + if (!expansion.isPresent()) { + return; + } + + suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1)); + } } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionInfo.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionInfo.java index d7b9b97..058b0a0 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionInfo.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionInfo.java @@ -23,6 +23,7 @@ package me.clip.placeholderapi.commands.impl.cloud; import java.util.List; import java.util.Optional; import java.util.stream.Stream; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.expansion.cloud.CloudExpansion; @@ -33,97 +34,97 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandECloudExpansionInfo extends PlaceholderCommand { - public CommandECloudExpansionInfo() { - super("info"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must specify the name of the expansion."); - return; + public CommandECloudExpansionInfo() { + super("info"); } - final CloudExpansion expansion = plugin.getCloudExpansionManager() - .findCloudExpansionByName(params.get(0)).orElse(null); - if (expansion == null) { - Msg.msg(sender, - "&cThere is no expansion with the name: &f" + params.get(0)); - return; + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must specify the name of the expansion."); + return; + } + + final CloudExpansion expansion = plugin.getCloudExpansionManager() + .findCloudExpansionByName(params.get(0)).orElse(null); + if (expansion == null) { + Msg.msg(sender, + "&cThere is no expansion with the name: &f" + params.get(0)); + return; + } + + final StringBuilder builder = new StringBuilder(); + + builder.append("&bExpansion: &f") + .append(expansion.shouldUpdate() ? "&e" : "&a") + .append(expansion.getName()) + .append('\n') + .append("&bAuthor: &f") + .append(expansion.getAuthor()) + .append('\n') + .append("&bVerified: ") + .append(expansion.isVerified() ? "&a&l✔" : "&c&l❌") + .append('\n'); + + if (params.size() < 2) { + builder.append("&bLatest Version: &f") + .append(expansion.getLatestVersion()) + .append('\n') + .append("&bReleased: &f") + .append(expansion.getTimeSinceLastUpdate()) + .append(" ago") + .append('\n') + .append("&bRelease Notes: &f") + .append(expansion.getVersion().getReleaseNotes()) + .append('\n'); + } else { + final CloudExpansion.Version version = expansion.getVersion(params.get(1)); + if (version == null) { + Msg.msg(sender, + "&cCould not find specified version: &f" + params.get(1), + "&aVersions: &f" + expansion.getAvailableVersions()); + return; + } + + builder.append("&bVersion: &f") + .append(version.getVersion()) + .append('\n') + .append("&bRelease Notes: &f") + .append(version.getReleaseNotes()) + .append('\n') + .append("&bDownload URL: &f") + .append(version.getUrl()) + .append('\n'); + } + + Msg.msg(sender, builder.toString()); } - final StringBuilder builder = new StringBuilder(); + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 2) { + return; + } - builder.append("&bExpansion: &f") - .append(expansion.shouldUpdate() ? "&e" : "&a") - .append(expansion.getName()) - .append('\n') - .append("&bAuthor: &f") - .append(expansion.getAuthor()) - .append('\n') - .append("&bVerified: ") - .append(expansion.isVerified() ? "&a&l✔" : "&c&l❌") - .append('\n'); + if (params.size() <= 1) { + final Stream names = plugin.getCloudExpansionManager().getCloudExpansions().values() + .stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_')); + suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); + return; + } - if (params.size() < 2) { - builder.append("&bLatest Version: &f") - .append(expansion.getLatestVersion()) - .append('\n') - .append("&bReleased: &f") - .append(expansion.getTimeSinceLastUpdate()) - .append(" ago") - .append('\n') - .append("&bRelease Notes: &f") - .append(expansion.getVersion().getReleaseNotes()) - .append('\n'); - } else { - final CloudExpansion.Version version = expansion.getVersion(params.get(1)); - if (version == null) { - Msg.msg(sender, - "&cCould not find specified version: &f" + params.get(1), - "&aVersions: &f" + expansion.getAvailableVersions()); - return; - } + final Optional expansion = plugin.getCloudExpansionManager() + .findCloudExpansionByName(params.get(0)); + if (!expansion.isPresent()) { + return; + } - builder.append("&bVersion: &f") - .append(version.getVersion()) - .append('\n') - .append("&bRelease Notes: &f") - .append(version.getReleaseNotes()) - .append('\n') - .append("&bDownload URL: &f") - .append(version.getUrl()) - .append('\n'); + suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1)); } - Msg.msg(sender, builder.toString()); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 2) { - return; - } - - if (params.size() <= 1) { - final Stream names = plugin.getCloudExpansionManager().getCloudExpansions().values() - .stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_')); - suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); - return; - } - - final Optional expansion = plugin.getCloudExpansionManager() - .findCloudExpansionByName(params.get(0)); - if (!expansion.isPresent()) { - return; - } - - suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1)); - } - } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionList.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionList.java index e5075bb..2f47036 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionList.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionList.java @@ -25,12 +25,14 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.primitives.Ints; + import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.configuration.ExpansionSort; @@ -54,299 +56,299 @@ import static net.kyori.adventure.text.format.NamedTextColor.*; public final class CommandECloudExpansionList extends PlaceholderCommand { - private static final int PAGE_SIZE = 10; + private static final int PAGE_SIZE = 10; - @NotNull - private static final Function EXPANSION_NAME = - expansion -> (expansion.shouldUpdate() ? "&6" : expansion.hasExpansion() ? "&a" : "&7") - + expansion.getName(); - @NotNull - private static final Function EXPANSION_AUTHOR = - expansion -> "&f" + expansion.getAuthor(); - @NotNull - private static final Function EXPANSION_VERIFIED = - expansion -> expansion.isVerified() ? "&aY" : "&cN"; - @NotNull - private static final Function EXPANSION_LATEST_VERSION = - expansion -> "&f" + expansion.getLatestVersion(); - @NotNull - private static final Function EXPANSION_CURRENT_VERSION = - expansion -> "&f" + PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() - .findExpansionByName(expansion.getName()).map(PlaceholderExpansion::getVersion) - .orElse("Unknown"); + @NotNull + private static final Function EXPANSION_NAME = + expansion -> (expansion.shouldUpdate() ? "&6" : expansion.hasExpansion() ? "&a" : "&7") + + expansion.getName(); + @NotNull + private static final Function EXPANSION_AUTHOR = + expansion -> "&f" + expansion.getAuthor(); + @NotNull + private static final Function EXPANSION_VERIFIED = + expansion -> expansion.isVerified() ? "&aY" : "&cN"; + @NotNull + private static final Function EXPANSION_LATEST_VERSION = + expansion -> "&f" + expansion.getLatestVersion(); + @NotNull + private static final Function EXPANSION_CURRENT_VERSION = + expansion -> "&f" + PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() + .findExpansionByName(expansion.getName()).map(PlaceholderExpansion::getVersion) + .orElse("Unknown"); - @Unmodifiable - private static final Set OPTIONS = ImmutableSet.of("all", "installed"); + @Unmodifiable + private static final Set OPTIONS = ImmutableSet.of("all", "installed"); - public CommandECloudExpansionList() { - super("list"); - } - - @NotNull - private static Collection getExpansions(@NotNull final String target, - @NotNull final PlaceholderAPIPlugin plugin) { - switch (target.toLowerCase(Locale.ROOT)) { - case "all": - return plugin.getCloudExpansionManager().getCloudExpansions().values(); - case "installed": - return plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values(); - default: - return plugin.getCloudExpansionManager().getCloudExpansionsByAuthor(target).values(); - } - } - - @NotNull - private static List getPage(@NotNull final List expansions, - final int page) { - final int head = (page * PAGE_SIZE); - final int tail = Math.min(expansions.size(), head + PAGE_SIZE); - - if (expansions.size() < head) { - return Collections.emptyList(); + public CommandECloudExpansionList() { + super("list"); } - return expansions.subList(head, tail); - } - - public static void addExpansionTitle(@NotNull final StringBuilder builder, - @NotNull final String target, final int page) { - switch (target.toLowerCase(Locale.ROOT)) { - case "all": - builder.append("&bAll Expansions"); - break; - case "installed": - builder.append("&bInstalled Expansions"); - break; - default: - builder.append("&bExpansions by &f") - .append(target); - break; - } - - if (page == -1) { - builder.append('\n'); - return; - } - - builder.append(" &bPage&7: &a") - .append(page) - .append("&r"); - } - - private static Component getMessage(@NotNull final List expansions, - final int page, final int limit, @NotNull final String target) { - final SimpleDateFormat format = PlaceholderAPIPlugin.getDateFormat(); - - final TextComponent.Builder message = text(); - - for (int index = 0; index < expansions.size(); index++) { - final CloudExpansion expansion = expansions.get(index); - final TextComponent.Builder line = text(); - - final int expansionNumber = index + ((page - 1) * PAGE_SIZE) + 1; - line.append(text(expansionNumber + ". ", DARK_GRAY)); - - final NamedTextColor expansionColour; - - if (expansion.shouldUpdate()) { - expansionColour = GOLD; - } else { - if (expansion.hasExpansion()) { - expansionColour = GREEN; - } else { - expansionColour = GRAY; + @NotNull + private static Collection getExpansions(@NotNull final String target, + @NotNull final PlaceholderAPIPlugin plugin) { + switch (target.toLowerCase(Locale.ROOT)) { + case "all": + return plugin.getCloudExpansionManager().getCloudExpansions().values(); + case "installed": + return plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values(); + default: + return plugin.getCloudExpansionManager().getCloudExpansionsByAuthor(target).values(); } - } - - line.append(text(expansion.getName(), expansionColour)); - - line.clickEvent(ClickEvent.suggestCommand("/papi ecloud download " + expansion.getName())); - - final TextComponent.Builder hoverText = text("Click to download this expansion!", AQUA) - .append(newline()).append(newline()) - .append(text("Author: ", AQUA)).append(text(expansion.getAuthor(), WHITE)) - .append(newline()) - .append(text("Verified: ", AQUA)).append(text(expansion.isVerified() ? "✔" : "❌", expansion.isVerified() ? GREEN : RED, TextDecoration.BOLD)) - .append(newline()) - .append(text("Released: ", AQUA)).append(text(format.format(expansion.getLastUpdate()), WHITE)) - .toBuilder(); - - Optional.ofNullable(expansion.getDescription()) - .filter(description -> !description.isEmpty()) - .ifPresent(description -> hoverText.append(newline()).append(newline()) - .append(text(description.replace("\r", "").trim(), WHITE)) - ); - - line.hoverEvent(HoverEvent.showText(hoverText.build())); - - if (index != expansions.size() - 1) { - line.append(newline()); - } - - message.append(line.build()); } - if (limit > 1) { - message.append(newline()); + @NotNull + private static List getPage(@NotNull final List expansions, + final int page) { + final int head = (page * PAGE_SIZE); + final int tail = Math.min(expansions.size(), head + PAGE_SIZE); - final TextComponent.Builder left = text("◀", page > 1 ? GRAY : DARK_GRAY).toBuilder(); + if (expansions.size() < head) { + return Collections.emptyList(); + } - if (page > 1) { - left.clickEvent(ClickEvent.runCommand("/papi ecloud list " + target + " " + (page - 1))); - } - - final TextComponent.Builder right = text("▶", page < limit ? GRAY : DARK_GRAY).toBuilder(); - - if (page < limit) { - right.clickEvent(ClickEvent.runCommand("/papi ecloud list " + target + " " + (page + 1))); - } - - message.append(left, text(" " + page + " ", GREEN), right); + return expansions.subList(head, tail); } - return message.build(); - } + public static void addExpansionTitle(@NotNull final StringBuilder builder, + @NotNull final String target, final int page) { + switch (target.toLowerCase(Locale.ROOT)) { + case "all": + builder.append("&bAll Expansions"); + break; + case "installed": + builder.append("&bInstalled Expansions"); + break; + default: + builder.append("&bExpansions by &f") + .append(target); + break; + } - private static void addExpansionTable(@NotNull final List expansions, - @NotNull final StringBuilder message, final int startIndex, - @NotNull final String versionTitle, - @NotNull final Function versionFunction) { - final Map> functions = new LinkedHashMap<>(); + if (page == -1) { + builder.append('\n'); + return; + } - final AtomicInteger counter = new AtomicInteger(startIndex); - functions.put("&f", expansion -> "&8" + counter.getAndIncrement() + "."); - - functions.put("&9Name", EXPANSION_NAME); - functions.put("&9Author", EXPANSION_AUTHOR); - functions.put("&9Verified", EXPANSION_VERIFIED); - functions.put(versionTitle, versionFunction); - - final List> rows = new ArrayList<>(); - - rows.add(0, new ArrayList<>(functions.keySet())); - - for (final CloudExpansion expansion : expansions) { - rows.add(functions.values().stream().map(function -> function.apply(expansion)) - .map(Objects::toString).collect(Collectors.toList())); + builder.append(" &bPage&7: &a") + .append(page) + .append("&r"); } - final List table = Format.tablify(Format.Align.LEFT, rows) - .orElse(Collections.emptyList()); - if (table.isEmpty()) { - return; + private static Component getMessage(@NotNull final List expansions, + final int page, final int limit, @NotNull final String target) { + final SimpleDateFormat format = PlaceholderAPIPlugin.getDateFormat(); + + final TextComponent.Builder message = text(); + + for (int index = 0; index < expansions.size(); index++) { + final CloudExpansion expansion = expansions.get(index); + final TextComponent.Builder line = text(); + + final int expansionNumber = index + ((page - 1) * PAGE_SIZE) + 1; + line.append(text(expansionNumber + ". ", DARK_GRAY)); + + final NamedTextColor expansionColour; + + if (expansion.shouldUpdate()) { + expansionColour = GOLD; + } else { + if (expansion.hasExpansion()) { + expansionColour = GREEN; + } else { + expansionColour = GRAY; + } + } + + line.append(text(expansion.getName(), expansionColour)); + + line.clickEvent(ClickEvent.suggestCommand("/papi ecloud download " + expansion.getName())); + + final TextComponent.Builder hoverText = text("Click to download this expansion!", AQUA) + .append(newline()).append(newline()) + .append(text("Author: ", AQUA)).append(text(expansion.getAuthor(), WHITE)) + .append(newline()) + .append(text("Verified: ", AQUA)).append(text(expansion.isVerified() ? "✔" : "❌", expansion.isVerified() ? GREEN : RED, TextDecoration.BOLD)) + .append(newline()) + .append(text("Released: ", AQUA)).append(text(format.format(expansion.getLastUpdate()), WHITE)) + .toBuilder(); + + Optional.ofNullable(expansion.getDescription()) + .filter(description -> !description.isEmpty()) + .ifPresent(description -> hoverText.append(newline()).append(newline()) + .append(text(description.replace("\r", "").trim(), WHITE)) + ); + + line.hoverEvent(HoverEvent.showText(hoverText.build())); + + if (index != expansions.size() - 1) { + line.append(newline()); + } + + message.append(line.build()); + } + + if (limit > 1) { + message.append(newline()); + + final TextComponent.Builder left = text("◀", page > 1 ? GRAY : DARK_GRAY).toBuilder(); + + if (page > 1) { + left.clickEvent(ClickEvent.runCommand("/papi ecloud list " + target + " " + (page - 1))); + } + + final TextComponent.Builder right = text("▶", page < limit ? GRAY : DARK_GRAY).toBuilder(); + + if (page < limit) { + right.clickEvent(ClickEvent.runCommand("/papi ecloud list " + target + " " + (page + 1))); + } + + message.append(left, text(" " + page + " ", GREEN), right); + } + + return message.build(); } - table.add(1, "&8" + Strings.repeat("-", table.get(0).length() - (rows.get(0).size() * 2))); + private static void addExpansionTable(@NotNull final List expansions, + @NotNull final StringBuilder message, final int startIndex, + @NotNull final String versionTitle, + @NotNull final Function versionFunction) { + final Map> functions = new LinkedHashMap<>(); - message.append(String.join("\n", table)); - } + final AtomicInteger counter = new AtomicInteger(startIndex); + functions.put("&f", expansion -> "&8" + counter.getAndIncrement() + "."); - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must specify an option. [all, {author}, installed]"); - return; + functions.put("&9Name", EXPANSION_NAME); + functions.put("&9Author", EXPANSION_AUTHOR); + functions.put("&9Verified", EXPANSION_VERIFIED); + functions.put(versionTitle, versionFunction); + + final List> rows = new ArrayList<>(); + + rows.add(0, new ArrayList<>(functions.keySet())); + + for (final CloudExpansion expansion : expansions) { + rows.add(functions.values().stream().map(function -> function.apply(expansion)) + .map(Objects::toString).collect(Collectors.toList())); + } + + final List table = Format.tablify(Format.Align.LEFT, rows) + .orElse(Collections.emptyList()); + if (table.isEmpty()) { + return; + } + + table.add(1, "&8" + Strings.repeat("-", table.get(0).length() - (rows.get(0).size() * 2))); + + message.append(String.join("\n", table)); } - final boolean installed = params.get(0).equalsIgnoreCase("installed"); - final List expansions = Lists - .newArrayList(getExpansions(params.get(0), plugin)); + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must specify an option. [all, {author}, installed]"); + return; + } - if (expansions.isEmpty()) { - Msg.msg(sender, - "&cNo expansions available to list."); - return; + final boolean installed = params.get(0).equalsIgnoreCase("installed"); + final List expansions = Lists + .newArrayList(getExpansions(params.get(0), plugin)); + + if (expansions.isEmpty()) { + Msg.msg(sender, + "&cNo expansions available to list."); + return; + } + + expansions + .sort(plugin.getPlaceholderAPIConfig().getExpansionSort().orElse(ExpansionSort.LATEST)); + + if (!(sender instanceof Player) && params.size() < 2) { + final StringBuilder builder = new StringBuilder(); + + addExpansionTitle(builder, params.get(0), -1); + addExpansionTable(expansions, + builder, + 1, + installed ? "&9Version" : "&9Latest Version", + installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); + + Msg.msg(sender, builder.toString()); + return; + } + + final int page; + + if (params.size() < 2) { + page = 1; + } else { + //noinspection UnstableApiUsage + final Integer parsed = Ints.tryParse(params.get(1)); + if (parsed == null) { + Msg.msg(sender, + "&cPage number must be an integer."); + return; + } + + final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); + + if (parsed < 1 || parsed > limit) { + Msg.msg(sender, + "&cPage number must be in the range &8[&a1&7..&a" + limit + "&8]"); + return; + } + + page = parsed; + } + + final StringBuilder builder = new StringBuilder(); + final List values = getPage(expansions, page - 1); + + addExpansionTitle(builder, params.get(0), page); + + if (!(sender instanceof Player)) { + addExpansionTable(values, + builder, + ((page - 1) * PAGE_SIZE) + 1, + installed ? "&9Version" : "&9Latest Version", + installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); + + Msg.msg(sender, builder.toString()); + + return; + } + + Msg.msg(sender, builder.toString()); + + final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); + + final Component message = getMessage(values, page, limit, params.get(0)); + plugin.getAdventure().player((Player) sender).sendMessage(message); } - expansions - .sort(plugin.getPlaceholderAPIConfig().getExpansionSort().orElse(ExpansionSort.LATEST)); + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 2) { + return; + } - if (!(sender instanceof Player) && params.size() < 2) { - final StringBuilder builder = new StringBuilder(); + if (params.size() <= 1) { + suggestByParameter( + Sets.union(OPTIONS, plugin.getCloudExpansionManager().getCloudExpansionAuthors()) + .stream(), suggestions, params.isEmpty() ? null : params.get(0)); + return; + } - addExpansionTitle(builder, params.get(0), -1); - addExpansionTable(expansions, - builder, - 1, - installed ? "&9Version" : "&9Latest Version", - installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); - - Msg.msg(sender, builder.toString()); - return; + suggestByParameter(IntStream.rangeClosed(1, + (int) Math.ceil((double) getExpansions(params.get(0), plugin).size() / PAGE_SIZE)) + .mapToObj(Objects::toString), suggestions, params.get(1)); } - final int page; - - if (params.size() < 2) { - page = 1; - } else { - //noinspection UnstableApiUsage - final Integer parsed = Ints.tryParse(params.get(1)); - if (parsed == null) { - Msg.msg(sender, - "&cPage number must be an integer."); - return; - } - - final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); - - if (parsed < 1 || parsed > limit) { - Msg.msg(sender, - "&cPage number must be in the range &8[&a1&7..&a" + limit + "&8]"); - return; - } - - page = parsed; - } - - final StringBuilder builder = new StringBuilder(); - final List values = getPage(expansions, page - 1); - - addExpansionTitle(builder, params.get(0), page); - - if (!(sender instanceof Player)) { - addExpansionTable(values, - builder, - ((page - 1) * PAGE_SIZE) + 1, - installed ? "&9Version" : "&9Latest Version", - installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); - - Msg.msg(sender, builder.toString()); - - return; - } - - Msg.msg(sender, builder.toString()); - - final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); - - final Component message = getMessage(values, page, limit, params.get(0)); - plugin.getAdventure().player((Player) sender).sendMessage(message); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 2) { - return; - } - - if (params.size() <= 1) { - suggestByParameter( - Sets.union(OPTIONS, plugin.getCloudExpansionManager().getCloudExpansionAuthors()) - .stream(), suggestions, params.isEmpty() ? null : params.get(0)); - return; - } - - suggestByParameter(IntStream.rangeClosed(1, - (int) Math.ceil((double) getExpansions(params.get(0), plugin).size() / PAGE_SIZE)) - .mapToObj(Objects::toString), suggestions, params.get(1)); - } - } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionPlaceholders.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionPlaceholders.java index f379365..3fcab71 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionPlaceholders.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionPlaceholders.java @@ -21,9 +21,11 @@ package me.clip.placeholderapi.commands.impl.cloud; import com.google.common.collect.Lists; + import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.expansion.cloud.CloudExpansion; @@ -34,61 +36,61 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandECloudExpansionPlaceholders extends PlaceholderCommand { - public CommandECloudExpansionPlaceholders() { - super("placeholders"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must specify the name of the expansion."); - return; + public CommandECloudExpansionPlaceholders() { + super("placeholders"); } - final CloudExpansion expansion = plugin.getCloudExpansionManager() - .findCloudExpansionByName(params.get(0)).orElse(null); - if (expansion == null) { - Msg.msg(sender, - "&cThere is no expansion with the name: &f" + params.get(0)); - return; + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must specify the name of the expansion."); + return; + } + + final CloudExpansion expansion = plugin.getCloudExpansionManager() + .findCloudExpansionByName(params.get(0)).orElse(null); + if (expansion == null) { + Msg.msg(sender, + "&cThere is no expansion with the name: &f" + params.get(0)); + return; + } + + final List placeholders = expansion.getPlaceholders(); + if (placeholders == null || placeholders.isEmpty()) { + Msg.msg(sender, + "&cThe expansion specified does not have placeholders listed."); + return; + } + + final List> partitions = Lists + .partition(placeholders.stream().sorted().collect(Collectors.toList()), 10); + + Msg.msg(sender, + "&6" + placeholders.size() + "&7 placeholders: &a", + partitions.stream().map(partition -> String.join(", ", partition)) + .collect(Collectors.joining("\n"))); + } - final List placeholders = expansion.getPlaceholders(); - if (placeholders == null || placeholders.isEmpty()) { - Msg.msg(sender, - "&cThe expansion specified does not have placeholders listed."); - return; + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 1) { + return; + } + + final Stream names = plugin.getCloudExpansionManager() + .getCloudExpansions() + .values() + .stream() + .map(CloudExpansion::getName) + .map(name -> name.replace(' ', '_')); + + suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); } - final List> partitions = Lists - .partition(placeholders.stream().sorted().collect(Collectors.toList()), 10); - - Msg.msg(sender, - "&6" + placeholders.size() + "&7 placeholders: &a", - partitions.stream().map(partition -> String.join(", ", partition)) - .collect(Collectors.joining("\n"))); - - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 1) { - return; - } - - final Stream names = plugin.getCloudExpansionManager() - .getCloudExpansions() - .values() - .stream() - .map(CloudExpansion::getName) - .map(name -> name.replace(' ', '_')); - - suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); - } - } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudRefresh.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudRefresh.java index c814d9e..b64dd92 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudRefresh.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudRefresh.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.commands.impl.cloud; import java.util.List; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.util.Msg; @@ -30,18 +31,18 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandECloudRefresh extends PlaceholderCommand { - public CommandECloudRefresh() { - super("refresh"); - } + public CommandECloudRefresh() { + super("refresh"); + } - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - plugin.getCloudExpansionManager().load(); + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + plugin.getCloudExpansionManager().load(); - Msg.msg(sender, - "&aThe eCloud manager has been refreshed!"); - } + Msg.msg(sender, + "&aThe eCloud manager has been refreshed!"); + } } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudStatus.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudStatus.java index b9b7ee6..e921187 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudStatus.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudStatus.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.commands.impl.cloud; import java.util.List; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.expansion.manager.CloudExpansionManager; @@ -31,34 +32,34 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandECloudStatus extends PlaceholderCommand { - public CommandECloudStatus() { - super("status"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - final CloudExpansionManager manager = plugin.getCloudExpansionManager(); - - final int updateCount = manager.getCloudUpdateCount(); - final int authorCount = manager.getCloudExpansionAuthorCount(); - final int expansionCount = manager.getCloudExpansions().size(); - - final StringBuilder builder = new StringBuilder(); - - builder.append("&bThere are &a").append(expansionCount) - .append("&b expansions available on the eCloud.").append('\n'); - builder.append("&7A total of &f").append(authorCount) - .append("&7 authors have contributed to the eCloud.").append('\n'); - - if (updateCount > 0) { - builder.append("&eYou have &f").append(updateCount) - .append(updateCount > 1 ? "&e expansions" : "&e expansion").append(" installed that ") - .append(updateCount > 1 ? "have an" : "has an").append(" update available."); + public CommandECloudStatus() { + super("status"); } - Msg.msg(sender, builder.toString()); - } + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + final CloudExpansionManager manager = plugin.getCloudExpansionManager(); + + final int updateCount = manager.getCloudUpdateCount(); + final int authorCount = manager.getCloudExpansionAuthorCount(); + final int expansionCount = manager.getCloudExpansions().size(); + + final StringBuilder builder = new StringBuilder(); + + builder.append("&bThere are &a").append(expansionCount) + .append("&b expansions available on the eCloud.").append('\n'); + builder.append("&7A total of &f").append(authorCount) + .append("&7 authors have contributed to the eCloud.").append('\n'); + + if (updateCount > 0) { + builder.append("&eYou have &f").append(updateCount) + .append(updateCount > 1 ? "&e expansions" : "&e expansion").append(" installed that ") + .append(updateCount > 1 ? "have an" : "has an").append(" update available."); + } + + Msg.msg(sender, builder.toString()); + } } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudUpdate.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudUpdate.java index 4aa8454..1a33d92 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudUpdate.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudUpdate.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.commands.impl.cloud; import com.google.common.collect.Lists; + import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -28,6 +29,7 @@ import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.expansion.PlaceholderExpansion; @@ -44,98 +46,98 @@ import org.jetbrains.annotations.Unmodifiable; */ public final class CommandECloudUpdate extends PlaceholderCommand { - public CommandECloudUpdate() { - super("update"); - } - - private static CompletableFuture>> downloadAndDiscover( - @NotNull final List expansions, @NotNull final PlaceholderAPIPlugin plugin) { - return expansions.stream() - .map(expansion -> plugin.getCloudExpansionManager() - .downloadExpansion(expansion, expansion.getVersion())) - .map(future -> future.thenCompose(plugin.getLocalExpansionManager()::findExpansionInFile)) - .collect(Futures.collector()); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must define 'all' or the name of an expansion to update."); - return; + public CommandECloudUpdate() { + super("update"); } - final boolean multiple = params.get(0).equalsIgnoreCase("all"); - final List expansions = new ArrayList<>(); - - // gather target expansions - if (multiple) { - expansions.addAll(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values()); - } else { - plugin.getCloudExpansionManager().findCloudExpansionByName(params.get(0)) - .ifPresent(expansions::add); + private static CompletableFuture>> downloadAndDiscover( + @NotNull final List expansions, @NotNull final PlaceholderAPIPlugin plugin) { + return expansions.stream() + .map(expansion -> plugin.getCloudExpansionManager() + .downloadExpansion(expansion, expansion.getVersion())) + .map(future -> future.thenCompose(plugin.getLocalExpansionManager()::findExpansionInFile)) + .collect(Futures.collector()); } - // remove the ones that are the latest version - expansions.removeIf(expansion -> !expansion.shouldUpdate()); + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must define 'all' or the name of an expansion to update."); + return; + } - if (expansions.isEmpty()) { - Msg.msg(sender, - "&cNo updates available for " + (!multiple ? "this expansion." - : "your active expansions.")); - return; - } + final boolean multiple = params.get(0).equalsIgnoreCase("all"); + final List expansions = new ArrayList<>(); - Msg.msg(sender, - "&aUpdating expansions: " + expansions.stream().map(CloudExpansion::getName) - .collect(Collectors.joining("&7, &6", "&8[&6", "&8]&r"))); + // gather target expansions + if (multiple) { + expansions.addAll(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values()); + } else { + plugin.getCloudExpansionManager().findCloudExpansionByName(params.get(0)) + .ifPresent(expansions::add); + } + + // remove the ones that are the latest version + expansions.removeIf(expansion -> !expansion.shouldUpdate()); + + if (expansions.isEmpty()) { + Msg.msg(sender, + "&cNo updates available for " + (!multiple ? "this expansion." + : "your active expansions.")); + return; + } - Futures.onMainThread(plugin, downloadAndDiscover(expansions, plugin), (classes, exception) -> { - if (exception != null) { Msg.msg(sender, - "&cFailed to update expansions: &e" + exception.getMessage()); - return; - } + "&aUpdating expansions: " + expansions.stream().map(CloudExpansion::getName) + .collect(Collectors.joining("&7, &6", "&8[&6", "&8]&r"))); - Msg.msg(sender, - "&aSuccessfully downloaded updates, registering new versions."); + Futures.onMainThread(plugin, downloadAndDiscover(expansions, plugin), (classes, exception) -> { + if (exception != null) { + Msg.msg(sender, + "&cFailed to update expansions: &e" + exception.getMessage()); + return; + } - final String message = classes.stream() - .filter(Objects::nonNull) - .map(plugin.getLocalExpansionManager()::register) - .filter(Optional::isPresent) - .map(Optional::get) - .map(expansion -> " &a" + expansion.getName() + " &f" + expansion.getVersion()) - .collect(Collectors.joining("\n")); + Msg.msg(sender, + "&aSuccessfully downloaded updates, registering new versions."); - Msg.msg(sender, - "&7Registered expansions:", message); + final String message = classes.stream() + .filter(Objects::nonNull) + .map(plugin.getLocalExpansionManager()::register) + .filter(Optional::isPresent) + .map(Optional::get) + .map(expansion -> " &a" + expansion.getName() + " &f" + expansion.getVersion()) + .collect(Collectors.joining("\n")); - }); - } + Msg.msg(sender, + "&7Registered expansions:", message); - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 1) { - return; + }); } - final List installed = Lists - .newArrayList(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values()); - installed.removeIf(expansion -> !expansion.shouldUpdate()); + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 1) { + return; + } - if (!installed.isEmpty() && (params.isEmpty() || "all" - .startsWith(params.get(0).toLowerCase(Locale.ROOT)))) { - suggestions.add("all"); + final List installed = Lists + .newArrayList(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values()); + installed.removeIf(expansion -> !expansion.shouldUpdate()); + + if (!installed.isEmpty() && (params.isEmpty() || "all" + .startsWith(params.get(0).toLowerCase(Locale.ROOT)))) { + suggestions.add("all"); + } + + suggestByParameter( + installed.stream().map(CloudExpansion::getName).map(name -> name.replace(" ", "_")), + suggestions, params.isEmpty() ? null : params.get(0)); } - suggestByParameter( - installed.stream().map(CloudExpansion::getName).map(name -> name.replace(" ", "_")), - suggestions, params.isEmpty() ? null : params.get(0)); - } - } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandDump.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandDump.java index f9d848a..23555e1 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandDump.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandDump.java @@ -54,160 +54,160 @@ import java.util.stream.Collectors; public final class CommandDump extends PlaceholderCommand { - @NotNull - private static final String URL = "https://paste.helpch.at/"; + @NotNull + private static final String URL = "https://paste.helpch.at/"; - @NotNull - private static final Gson gson = new Gson(); + @NotNull + private static final Gson gson = new Gson(); - @NotNull - private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter - .ofLocalizedDateTime(FormatStyle.LONG) - .withLocale(Locale.US) - .withZone(ZoneId.of("UTC")); + @NotNull + private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter + .ofLocalizedDateTime(FormatStyle.LONG) + .withLocale(Locale.US) + .withZone(ZoneId.of("UTC")); - public CommandDump() { - super("dump"); - } + public CommandDump() { + super("dump"); + } - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - postDump(makeDump(plugin)).whenComplete((key, exception) -> { - if (exception != null) { - plugin.getLogger().log(Level.WARNING, "failed to post dump details", exception); + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + postDump(makeDump(plugin)).whenComplete((key, exception) -> { + if (exception != null) { + plugin.getLogger().log(Level.WARNING, "failed to post dump details", exception); - Msg.msg(sender, - "&cFailed to post dump details, check console."); - return; - } + Msg.msg(sender, + "&cFailed to post dump details, check console."); + return; + } - Msg.msg(sender, - "&aSuccessfully posted dump: " + URL + key); - }); - } + Msg.msg(sender, + "&aSuccessfully posted dump: " + URL + key); + }); + } - @NotNull - private CompletableFuture postDump(@NotNull final String dump) { - return CompletableFuture.supplyAsync(() -> { - try { - final HttpURLConnection connection = ((HttpURLConnection) new URL(URL + "documents") - .openConnection()); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); - connection.setDoOutput(true); + @NotNull + private CompletableFuture postDump(@NotNull final String dump) { + return CompletableFuture.supplyAsync(() -> { + try { + final HttpURLConnection connection = ((HttpURLConnection) new URL(URL + "documents") + .openConnection()); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); + connection.setDoOutput(true); - connection.connect(); + connection.connect(); + + try (final OutputStream stream = connection.getOutputStream()) { + stream.write(dump.getBytes(StandardCharsets.UTF_8)); + } + + try (final InputStream stream = connection.getInputStream()) { + final String json = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8)); + return gson.fromJson(json, JsonObject.class).get("key").getAsString(); + } + } catch (final IOException ex) { + throw new CompletionException(ex); + } + }); + } + + @NotNull + private String makeDump(@NotNull final PlaceholderAPIPlugin plugin) { + final StringBuilder builder = new StringBuilder(); + + builder.append("Generated: ") + .append(DATE_FORMAT.format(Instant.now())) + .append("\n\n"); + + builder.append("PlaceholderAPI: ") + .append(plugin.getDescription().getVersion()) + .append("\n\n"); + + builder.append("Expansions Registered:") + .append('\n'); + + final List expansions = plugin.getLocalExpansionManager() + .getExpansions() + .stream() + .sorted( + Comparator.comparing(PlaceholderExpansion::getIdentifier) + .thenComparing(PlaceholderExpansion::getAuthor) + ) + .collect(Collectors.toList()); + + int size = expansions.stream().map(e -> e.getIdentifier().length()) + .max(Integer::compareTo) + .orElse(0); + + for (final PlaceholderExpansion expansion : expansions) { + builder.append(" ") + .append(String.format("%-" + size + "s", expansion.getIdentifier())) + .append(" [Author: ") + .append(expansion.getAuthor()) + .append(", Version: ") + .append(expansion.getVersion()) + .append("]\n"); - try (final OutputStream stream = connection.getOutputStream()) { - stream.write(dump.getBytes(StandardCharsets.UTF_8)); } - try (final InputStream stream = connection.getInputStream()) { - final String json = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8)); - return gson.fromJson(json, JsonObject.class).get("key").getAsString(); + builder.append('\n'); + + builder.append("Expansions Directory:") + .append('\n'); + + final String[] jars = plugin.getLocalExpansionManager() + .getExpansionsFolder() + .list((dir, name) -> name.toLowerCase(Locale.ROOT).endsWith(".jar")); + + + if (jars == null) { + builder.append(" ¨[Warning]: Could not load jar files from expansions folder."); + } else { + for (final String jar : jars) { + builder.append(" ") + .append(jar) + .append('\n'); + } } - } catch (final IOException ex) { - throw new CompletionException(ex); - } - }); - } - @NotNull - private String makeDump(@NotNull final PlaceholderAPIPlugin plugin) { - final StringBuilder builder = new StringBuilder(); + builder.append('\n'); - builder.append("Generated: ") - .append(DATE_FORMAT.format(Instant.now())) - .append("\n\n"); + builder.append("Server Info: ") + .append(plugin.getServer().getBukkitVersion()) + .append('/') + .append(plugin.getServer().getVersion()) + .append("\n"); - builder.append("PlaceholderAPI: ") - .append(plugin.getDescription().getVersion()) - .append("\n\n"); + builder.append("Java Version: ") + .append(System.getProperty("java.version")) + .append("\n\n"); - builder.append("Expansions Registered:") - .append('\n'); + builder.append("Plugin Info:") + .append('\n'); - final List expansions = plugin.getLocalExpansionManager() - .getExpansions() - .stream() - .sorted( - Comparator.comparing(PlaceholderExpansion::getIdentifier) - .thenComparing(PlaceholderExpansion::getAuthor) - ) - .collect(Collectors.toList()); + List plugins = Arrays.stream(plugin.getServer().getPluginManager().getPlugins()) + .sorted(Comparator.comparing(Plugin::getName)) + .collect(Collectors.toList()); - int size = expansions.stream().map(e -> e.getIdentifier().length()) - .max(Integer::compareTo) - .orElse(0); + size = plugins.stream().map(pl -> pl.getName().length()) + .max(Integer::compareTo) + .orElse(0); - for (final PlaceholderExpansion expansion : expansions) { - builder.append(" ") - .append(String.format("%-" + size + "s", expansion.getIdentifier())) - .append(" [Author: ") - .append(expansion.getAuthor()) - .append(", Version: ") - .append(expansion.getVersion()) - .append("]\n"); + for (final Plugin other : plugins) { + builder.append(" ") + .append(String.format("%-" + size + "s", other.getName())) + .append(" [Authors: [") + .append(String.join(", ", other.getDescription().getAuthors())) + .append("], Version: ") + .append(other.getDescription().getVersion()) + .append("]") + .append("\n"); + } + return builder.toString(); } - - builder.append('\n'); - - builder.append("Expansions Directory:") - .append('\n'); - - final String[] jars = plugin.getLocalExpansionManager() - .getExpansionsFolder() - .list((dir, name) -> name.toLowerCase(Locale.ROOT).endsWith(".jar")); - - - if (jars == null) { - builder.append(" ¨[Warning]: Could not load jar files from expansions folder."); - } else { - for (final String jar : jars) { - builder.append(" ") - .append(jar) - .append('\n'); - } - } - - builder.append('\n'); - - builder.append("Server Info: ") - .append(plugin.getServer().getBukkitVersion()) - .append('/') - .append(plugin.getServer().getVersion()) - .append("\n"); - - builder.append("Java Version: ") - .append(System.getProperty("java.version")) - .append("\n\n"); - - builder.append("Plugin Info:") - .append('\n'); - - List plugins = Arrays.stream(plugin.getServer().getPluginManager().getPlugins()) - .sorted(Comparator.comparing(Plugin::getName)) - .collect(Collectors.toList()); - - size = plugins.stream().map(pl -> pl.getName().length()) - .max(Integer::compareTo) - .orElse(0); - - for (final Plugin other : plugins) { - builder.append(" ") - .append(String.format("%-" + size + "s", other.getName())) - .append(" [Authors: [") - .append(String.join(", ", other.getDescription().getAuthors())) - .append("], Version: ") - .append(other.getDescription().getVersion()) - .append("]") - .append("\n"); - } - - return builder.toString(); - } } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionRegister.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionRegister.java index a37d793..0544204 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionRegister.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionRegister.java @@ -25,6 +25,7 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.logging.Level; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.expansion.PlaceholderExpansion; @@ -37,74 +38,74 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandExpansionRegister extends PlaceholderCommand { - public CommandExpansionRegister() { - super("register"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.size() < 1) { - Msg.msg(sender, - "&cYou must specify the name of an expansion file."); - return; + public CommandExpansionRegister() { + super("register"); } - final LocalExpansionManager manager = plugin.getLocalExpansionManager(); + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.size() < 1) { + Msg.msg(sender, + "&cYou must specify the name of an expansion file."); + return; + } - final File file = new File(manager.getExpansionsFolder(), params.get(0)); - if (!file.exists() || !file.getParentFile().equals(manager.getExpansionsFolder())) { - Msg.msg(sender, - "&cThe file &f" + file.getName() + "&c doesn't exist!"); - return; + final LocalExpansionManager manager = plugin.getLocalExpansionManager(); + + final File file = new File(manager.getExpansionsFolder(), params.get(0)); + if (!file.exists() || !file.getParentFile().equals(manager.getExpansionsFolder())) { + Msg.msg(sender, + "&cThe file &f" + file.getName() + "&c doesn't exist!"); + return; + } + + Futures.onMainThread(plugin, manager.findExpansionInFile(file), (clazz, exception) -> { + if (exception != null) { + Msg.msg(sender, + "&cFailed to find expansion in file: &f" + file); + + plugin.getLogger() + .log(Level.WARNING, "failed to find expansion in file: " + file, exception); + return; + } + + if (clazz == null) { + Msg.msg(sender, + "&cNo expansion class found in file: &f" + file); + return; + } + + final Optional expansion = manager.register(clazz); + if (!expansion.isPresent()) { + Msg.msg(sender, + "&cFailed to register expansion from &f" + params.get(0)); + return; + } + + Msg.msg(sender, + "&aSuccessfully registered expansion: &f" + expansion.get().getName()); + + }); } - Futures.onMainThread(plugin, manager.findExpansionInFile(file), (clazz, exception) -> { - if (exception != null) { - Msg.msg(sender, - "&cFailed to find expansion in file: &f" + file); + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 1) { + return; + } - plugin.getLogger() - .log(Level.WARNING, "failed to find expansion in file: " + file, exception); - return; - } + final String[] fileNames = plugin.getLocalExpansionManager().getExpansionsFolder() + .list((dir, name) -> name.endsWith(".jar")); + if (fileNames == null || fileNames.length == 0) { + return; + } - if (clazz == null) { - Msg.msg(sender, - "&cNo expansion class found in file: &f" + file); - return; - } - - final Optional expansion = manager.register(clazz); - if (!expansion.isPresent()) { - Msg.msg(sender, - "&cFailed to register expansion from &f" + params.get(0)); - return; - } - - Msg.msg(sender, - "&aSuccessfully registered expansion: &f" + expansion.get().getName()); - - }); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 1) { - return; + suggestByParameter(Arrays.stream(fileNames), suggestions, + params.isEmpty() ? null : params.get(0)); } - final String[] fileNames = plugin.getLocalExpansionManager().getExpansionsFolder() - .list((dir, name) -> name.endsWith(".jar")); - if (fileNames == null || fileNames.length == 0) { - return; - } - - suggestByParameter(Arrays.stream(fileNames), suggestions, - params.isEmpty() ? null : params.get(0)); - } - } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionUnregister.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionUnregister.java index ff6c6da..231a7c2 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionUnregister.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionUnregister.java @@ -22,6 +22,7 @@ package me.clip.placeholderapi.commands.impl.local; import java.util.List; import java.util.Optional; + import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; @@ -33,45 +34,45 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandExpansionUnregister extends PlaceholderCommand { - public CommandExpansionUnregister() { - super("unregister"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must specify the name of the expansion."); - return; + public CommandExpansionUnregister() { + super("unregister"); } - final Optional expansion = plugin.getLocalExpansionManager() - .findExpansionByName(params.get(0)); - if (!expansion.isPresent()) { - Msg.msg(sender, - "&cThere is no expansion loaded with the identifier: &f" + params.get(0)); - return; + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must specify the name of the expansion."); + return; + } + + final Optional expansion = plugin.getLocalExpansionManager() + .findExpansionByName(params.get(0)); + if (!expansion.isPresent()) { + Msg.msg(sender, + "&cThere is no expansion loaded with the identifier: &f" + params.get(0)); + return; + } + + final String message = !expansion.get().unregister() ? + "&cFailed to unregister expansion: &f" : + "&aSuccessfully unregistered expansion: &f"; + + Msg.msg(sender, message + expansion.get().getName()); } - final String message = !expansion.get().unregister() ? - "&cFailed to unregister expansion: &f" : - "&aSuccessfully unregistered expansion: &f"; + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 1) { + return; + } - Msg.msg(sender, message + expansion.get().getName()); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 1) { - return; + suggestByParameter(PlaceholderAPI.getRegisteredIdentifiers().stream(), suggestions, + params.isEmpty() ? null : params.get(0)); } - suggestByParameter(PlaceholderAPI.getRegisteredIdentifiers().stream(), suggestions, - params.isEmpty() ? null : params.get(0)); - } - } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandHelp.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandHelp.java index 47c1da8..f2b3bd1 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandHelp.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandHelp.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.commands.impl.local; import java.util.List; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.util.Msg; @@ -31,42 +32,42 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandHelp extends PlaceholderCommand { - public CommandHelp() { - super("help"); - } + public CommandHelp() { + super("help"); + } - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - final PluginDescriptionFile description = plugin.getDescription(); + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + final PluginDescriptionFile description = plugin.getDescription(); - Msg.msg(sender, - "&b&lPlaceholderAPI &8- &7Help Menu &8- &7(&f" + description.getVersion() + "&7)", - " ", - "&b/papi &fbcparse &9 ", - " &7&oParse a message with placeholders and broadcast it", - "&b/papi &fcmdparse &9 ", - " &7&oParse a message with relational placeholders", - "&b/papi &fdump", - " &7&oDump all relevant information needed to help debug issues into a paste link.", - "&b/papi &finfo &9", - " &7&oView information for a specific expansion", - "&b/papi &flist", - " &7&oList active expansions", - "&b/papi &fparse &9 ", - " &7&oParse a message with placeholders", - "&b/papi &fparserel &9 ", - " &7&oParse a message with relational placeholders", - "&b/papi &fregister &9", - " &7&oRegister an expansion by the name of the file", - "&b/papi &freload", - " &7&oReload the config of PAPI", - "&b/papi &funregister &9", - " &7&oUnregister an expansion by name", - "&b/papi &fversion", - " &7&oView plugin info/version"); - } + Msg.msg(sender, + "&b&lPlaceholderAPI &8- &7Help Menu &8- &7(&f" + description.getVersion() + "&7)", + " ", + "&b/papi &fbcparse &9 ", + " &7&oParse a message with placeholders and broadcast it", + "&b/papi &fcmdparse &9 ", + " &7&oParse a message with relational placeholders", + "&b/papi &fdump", + " &7&oDump all relevant information needed to help debug issues into a paste link.", + "&b/papi &finfo &9", + " &7&oView information for a specific expansion", + "&b/papi &flist", + " &7&oList active expansions", + "&b/papi &fparse &9 ", + " &7&oParse a message with placeholders", + "&b/papi &fparserel &9 ", + " &7&oParse a message with relational placeholders", + "&b/papi &fregister &9", + " &7&oRegister an expansion by the name of the file", + "&b/papi &freload", + " &7&oReload the config of PAPI", + "&b/papi &funregister &9", + " &7&oUnregister an expansion by name", + "&b/papi &fversion", + " &7&oView plugin info/version"); + } } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandInfo.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandInfo.java index 95e84c1..4badaf6 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandInfo.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandInfo.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.commands.impl.local; import java.util.List; + import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; @@ -32,82 +33,82 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandInfo extends PlaceholderCommand { - public CommandInfo() { - super("info"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must specify the name of the expansion."); - return; + public CommandInfo() { + super("info"); } - final PlaceholderExpansion expansion = plugin.getLocalExpansionManager() - .findExpansionByIdentifier(params.get(0)).orElse(null); - if (expansion == null) { - Msg.msg(sender, - "&cThere is no expansion loaded with the identifier: &f" + params.get(0)); - return; + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must specify the name of the expansion."); + return; + } + + final PlaceholderExpansion expansion = plugin.getLocalExpansionManager() + .findExpansionByIdentifier(params.get(0)).orElse(null); + if (expansion == null) { + Msg.msg(sender, + "&cThere is no expansion loaded with the identifier: &f" + params.get(0)); + return; + } + + final StringBuilder builder = new StringBuilder(); + + builder.append("&7Placeholder expansion info for: &r") + .append(expansion.getName()) + .append('\n') + .append("&7Status: &r") + .append(expansion.isRegistered() ? "&aRegistered" : "7cNotRegistered") + .append('\n'); + + final String author = expansion.getAuthor(); + if (author != null) { + builder.append("&7Author: &r") + .append(author) + .append('\n'); + } + + final String version = expansion.getVersion(); + if (version != null) { + builder.append("&7Version: &r") + .append(version) + .append('\n'); + } + + final String requiredPlugin = expansion.getRequiredPlugin(); + if (requiredPlugin != null) { + builder.append("&7Requires plugin: &r") + .append(requiredPlugin) + .append('\n'); + } + + final List placeholders = expansion.getPlaceholders(); + if (placeholders != null && !placeholders.isEmpty()) { + builder.append("&8&m-- &7Placeholders &8&m--&r") + .append('\n'); + + for (final String placeholder : placeholders) { + builder.append(placeholder) + .append('\n'); + } + } + + Msg.msg(sender, builder.toString()); } - final StringBuilder builder = new StringBuilder(); + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 1) { + return; + } - builder.append("&7Placeholder expansion info for: &r") - .append(expansion.getName()) - .append('\n') - .append("&7Status: &r") - .append(expansion.isRegistered() ? "&aRegistered" : "7cNotRegistered") - .append('\n'); - - final String author = expansion.getAuthor(); - if (author != null) { - builder.append("&7Author: &r") - .append(author) - .append('\n'); + suggestByParameter(PlaceholderAPI.getRegisteredIdentifiers().stream(), suggestions, + params.isEmpty() ? null : params.get(0)); } - final String version = expansion.getVersion(); - if (version != null) { - builder.append("&7Version: &r") - .append(version) - .append('\n'); - } - - final String requiredPlugin = expansion.getRequiredPlugin(); - if (requiredPlugin != null) { - builder.append("&7Requires plugin: &r") - .append(requiredPlugin) - .append('\n'); - } - - final List placeholders = expansion.getPlaceholders(); - if (placeholders != null && !placeholders.isEmpty()) { - builder.append("&8&m-- &7Placeholders &8&m--&r") - .append('\n'); - - for (final String placeholder : placeholders) { - builder.append(placeholder) - .append('\n'); - } - } - - Msg.msg(sender, builder.toString()); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 1) { - return; - } - - suggestByParameter(PlaceholderAPI.getRegisteredIdentifiers().stream(), suggestions, - params.isEmpty() ? null : params.get(0)); - } - } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandList.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandList.java index 0284b89..d3bf0d9 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandList.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandList.java @@ -21,9 +21,11 @@ package me.clip.placeholderapi.commands.impl.local; import com.google.common.collect.Lists; + import java.util.List; import java.util.Set; import java.util.stream.Collectors; + import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; @@ -34,28 +36,28 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandList extends PlaceholderCommand { - public CommandList() { - super("list"); - } - - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - final Set identifiers = PlaceholderAPI.getRegisteredIdentifiers(); - if (identifiers.isEmpty()) { - Msg.msg(sender, "&cThere are no placeholder hooks active!"); - return; + public CommandList() { + super("list"); } - final List> partitions = Lists - .partition(identifiers.stream().sorted().collect(Collectors.toList()), 10); - Msg.msg(sender, - "&7A total of &f" + identifiers.size() + "&7 placeholder hook(s) are active: &a", - partitions.stream().map(partition -> String.join("&7, &a", partition)) - .collect(Collectors.joining("\n"))); - } + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + final Set identifiers = PlaceholderAPI.getRegisteredIdentifiers(); + if (identifiers.isEmpty()) { + Msg.msg(sender, "&cThere are no placeholder hooks active!"); + return; + } + + final List> partitions = Lists + .partition(identifiers.stream().sorted().collect(Collectors.toList()), 10); + + Msg.msg(sender, + "&7A total of &f" + identifiers.size() + "&7 placeholder hook(s) are active: &a", + partitions.stream().map(partition -> String.join("&7, &a", partition)) + .collect(Collectors.joining("\n"))); + } } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandParse.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandParse.java index 1ff59b9..ad752ab 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandParse.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandParse.java @@ -25,6 +25,7 @@ import java.util.List; import java.util.Locale; import java.util.Set; import java.util.stream.Stream; + import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; @@ -40,217 +41,217 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandParse extends PlaceholderCommand { - public CommandParse() { - super("parse", "bcparse", "parserel", "cmdparse"); - } - - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - switch (alias.toLowerCase(Locale.ROOT)) { - case "parserel": - evaluateParseRelation(sender, params); - break; - case "parse": - evaluateParseSingular(sender, params, false, false); - break; - case "bcparse": - evaluateParseSingular(sender, params, true, false); - break; - case "cmdparse": - evaluateParseSingular(sender, params, false, true); - break; - } - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - switch (alias.toLowerCase(Locale.ROOT)) { - case "parserel": - completeParseRelation(params, suggestions); - break; - case "parse": - case "bcparse": - case "cmdparse": - completeParseSingular(sender, params, suggestions); - break; - } - } - - - private void evaluateParseSingular(@NotNull final CommandSender sender, - @NotNull @Unmodifiable final List params, final boolean broadcast, - final boolean command) { - if (params.size() < 2) { - Msg.msg(sender, - "&cYou must provide a target and message: &b/papi " - + (command ? "cmdparse" : (broadcast ? "bcparse" : "parse")) - + " &7{target} &a{message}"); - return; + public CommandParse() { + super("parse", "bcparse", "parserel", "cmdparse"); } - OfflinePlayer player; - if ("me".equalsIgnoreCase(params.get(0))) { - if (!(sender instanceof Player)) { - Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); - return; - } - - player = ((Player) sender); - } else if ("--null".equalsIgnoreCase(params.get(0))) { - player = null; - } else { - final OfflinePlayer target = resolvePlayer(params.get(0)); - if (target == null) { - Msg.msg(sender, "&cFailed to find player: &7" + params.get(0)); - return; - } - - player = target; + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + switch (alias.toLowerCase(Locale.ROOT)) { + case "parserel": + evaluateParseRelation(sender, params); + break; + case "parse": + evaluateParseSingular(sender, params, false, false); + break; + case "bcparse": + evaluateParseSingular(sender, params, true, false); + break; + case "cmdparse": + evaluateParseSingular(sender, params, false, true); + break; + } } - final String message = PlaceholderAPI - .setPlaceholders(player, String.join(" ", params.subList(1, params.size()))); - - if (command) { - Bukkit.dispatchCommand(sender, message); - return; + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + switch (alias.toLowerCase(Locale.ROOT)) { + case "parserel": + completeParseRelation(params, suggestions); + break; + case "parse": + case "bcparse": + case "cmdparse": + completeParseSingular(sender, params, suggestions); + break; + } } - if (broadcast) { - Bukkit.broadcastMessage(message); - } else { - sender.sendMessage(message); - } - } - private void evaluateParseRelation(@NotNull final CommandSender sender, - @NotNull @Unmodifiable final List params) { - if (params.size() < 3) { - Msg.msg(sender, - "&cYou must supply two targets, and a message: &b/papi parserel &7{target one} " - + "{target two} &a{message}"); - return; - } - - OfflinePlayer playerOne; - - if ("me".equalsIgnoreCase(params.get(0))) { - if (!(sender instanceof Player)) { - Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); - return; - } - - playerOne = ((Player) sender); - } else { - playerOne = resolvePlayer(params.get(0)); - } - - if (playerOne == null || !playerOne.isOnline()) { - Msg.msg(sender, "&cFailed to find player: &f" + params.get(0)); - return; - } - - OfflinePlayer playerTwo; - - if ("me".equalsIgnoreCase(params.get(1))) { - if (!(sender instanceof Player)) { - Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); - return; - } - - playerTwo = ((Player) sender); - } else { - playerTwo = resolvePlayer(params.get(1)); - } - - if (playerTwo == null || !playerTwo.isOnline()) { - Msg.msg(sender, "&cFailed to find player: &f" + params.get(1)); - return; + private void evaluateParseSingular(@NotNull final CommandSender sender, + @NotNull @Unmodifiable final List params, final boolean broadcast, + final boolean command) { + if (params.size() < 2) { + Msg.msg(sender, + "&cYou must provide a target and message: &b/papi " + + (command ? "cmdparse" : (broadcast ? "bcparse" : "parse")) + + " &7{target} &a{message}"); + return; + } + + OfflinePlayer player; + + if ("me".equalsIgnoreCase(params.get(0))) { + if (!(sender instanceof Player)) { + Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); + return; + } + + player = ((Player) sender); + } else if ("--null".equalsIgnoreCase(params.get(0))) { + player = null; + } else { + final OfflinePlayer target = resolvePlayer(params.get(0)); + if (target == null) { + Msg.msg(sender, "&cFailed to find player: &7" + params.get(0)); + return; + } + + player = target; + } + + final String message = PlaceholderAPI + .setPlaceholders(player, String.join(" ", params.subList(1, params.size()))); + + if (command) { + Bukkit.dispatchCommand(sender, message); + return; + } + + if (broadcast) { + Bukkit.broadcastMessage(message); + } else { + sender.sendMessage(message); + } } - final String message = PlaceholderAPI - .setRelationalPlaceholders((Player) playerOne, (Player) playerTwo, - String.join(" ", params.subList(2, params.size()))); - - sender.sendMessage(message); - } + private void evaluateParseRelation(@NotNull final CommandSender sender, + @NotNull @Unmodifiable final List params) { + if (params.size() < 3) { + Msg.msg(sender, + "&cYou must supply two targets, and a message: &b/papi parserel &7{target one} " + + "{target two} &a{message}"); + return; + } + OfflinePlayer playerOne; - private void completeParseSingular(@NotNull final CommandSender sender, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() <= 1) { - if (sender instanceof Player && (params.isEmpty() || "me" - .startsWith(params.get(0).toLowerCase(Locale.ROOT)))) { - suggestions.add("me"); - } - - if ("--null".startsWith(params.get(0).toLowerCase(Locale.ROOT))) { - suggestions.add("--null"); - } - - final Stream names = Bukkit.getOnlinePlayers().stream().map(Player::getName); - suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); + if ("me".equalsIgnoreCase(params.get(0))) { + if (!(sender instanceof Player)) { + Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); + return; + } - return; + playerOne = ((Player) sender); + } else { + playerOne = resolvePlayer(params.get(0)); + } + + if (playerOne == null || !playerOne.isOnline()) { + Msg.msg(sender, "&cFailed to find player: &f" + params.get(0)); + return; + } + + OfflinePlayer playerTwo; + + if ("me".equalsIgnoreCase(params.get(1))) { + if (!(sender instanceof Player)) { + Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); + return; + } + + playerTwo = ((Player) sender); + } else { + playerTwo = resolvePlayer(params.get(1)); + } + + if (playerTwo == null || !playerTwo.isOnline()) { + Msg.msg(sender, "&cFailed to find player: &f" + params.get(1)); + return; + } + + final String message = PlaceholderAPI + .setRelationalPlaceholders((Player) playerOne, (Player) playerTwo, + String.join(" ", params.subList(2, params.size()))); + + sender.sendMessage(message); } - final String name = params.get(params.size() - 1); - if (!name.startsWith("%") || name.endsWith("%")) { - return; + + private void completeParseSingular(@NotNull final CommandSender sender, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() <= 1) { + if (sender instanceof Player && (params.isEmpty() || "me" + .startsWith(params.get(0).toLowerCase(Locale.ROOT)))) { + suggestions.add("me"); + } + + if ("--null".startsWith(params.get(0).toLowerCase(Locale.ROOT))) { + suggestions.add("--null"); + } + + final Stream names = Bukkit.getOnlinePlayers().stream().map(Player::getName); + suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); + + return; + } + + final String name = params.get(params.size() - 1); + if (!name.startsWith("%") || name.endsWith("%")) { + return; + } + + final int index = name.indexOf('_'); + if (index == -1) { + return; // no arguments supplied yet + } + + final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() + .getLocalExpansionManager().findExpansionByIdentifier(name.substring(1, index)) + .orElse(null); + if (expansion == null) { + return; + } + + final Set possible = new HashSet<>(expansion.getPlaceholders()); + + PlaceholderAPIPlugin.getInstance() + .getCloudExpansionManager() + .findCloudExpansionByName(expansion.getName()) + .ifPresent(cloud -> possible.addAll(cloud.getPlaceholders())); + + suggestByParameter(possible.stream(), suggestions, params.get(params.size() - 1)); } - final int index = name.indexOf('_'); - if (index == -1) { - return; // no arguments supplied yet + private void completeParseRelation(@NotNull @Unmodifiable final List params, + @NotNull final List suggestions) { + if (params.size() > 2) { + return; + } + + final Stream names = Bukkit.getOnlinePlayers().stream().map(Player::getName); + suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(params.size() - 1)); } - final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() - .getLocalExpansionManager().findExpansionByIdentifier(name.substring(1, index)) - .orElse(null); - if (expansion == null) { - return; + + @Nullable + private OfflinePlayer resolvePlayer(@NotNull final String name) { + OfflinePlayer target = Bukkit.getPlayerExact(name); + + if (target == null) { + // Not the best option, but Spigot doesn't offer a good replacement (as usual) + target = Bukkit.getOfflinePlayer(name); + + return target.hasPlayedBefore() ? target : null; + } + + return target; + } - final Set possible = new HashSet<>(expansion.getPlaceholders()); - - PlaceholderAPIPlugin.getInstance() - .getCloudExpansionManager() - .findCloudExpansionByName(expansion.getName()) - .ifPresent(cloud -> possible.addAll(cloud.getPlaceholders())); - - suggestByParameter(possible.stream(), suggestions, params.get(params.size() - 1)); - } - - private void completeParseRelation(@NotNull @Unmodifiable final List params, - @NotNull final List suggestions) { - if (params.size() > 2) { - return; - } - - final Stream names = Bukkit.getOnlinePlayers().stream().map(Player::getName); - suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(params.size() - 1)); - } - - - @Nullable - private OfflinePlayer resolvePlayer(@NotNull final String name) { - OfflinePlayer target = Bukkit.getPlayerExact(name); - - if (target == null) { - // Not the best option, but Spigot doesn't offer a good replacement (as usual) - target = Bukkit.getOfflinePlayer(name); - - return target.hasPlayedBefore() ? target : null; - } - - return target; - - } - } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandReload.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandReload.java index 44e1b43..4f55359 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandReload.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandReload.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.commands.impl.local; import java.util.List; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import org.bukkit.command.CommandSender; @@ -29,15 +30,15 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandReload extends PlaceholderCommand { - public CommandReload() { - super("reload"); - } + public CommandReload() { + super("reload"); + } - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - plugin.reloadConf(sender); - } + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + plugin.reloadConf(sender); + } } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandVersion.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandVersion.java index f637d9c..939c63d 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandVersion.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandVersion.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.commands.impl.local; import java.util.List; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.util.Msg; @@ -31,22 +32,22 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandVersion extends PlaceholderCommand { - public CommandVersion() { - super("version"); - } + public CommandVersion() { + super("version"); + } - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - final PluginDescriptionFile description = plugin.getDescription(); + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + final PluginDescriptionFile description = plugin.getDescription(); - Msg.msg(sender, - "&b&lPlaceholderAPI &7(&f" + description.getVersion() + "&7)", - "&7Author: &f" + description.getAuthors(), - "&7PAPI Commands: &b/papi &fhelp", - "&7eCloud Commands&8: &b/papi &fecloud"); - } + Msg.msg(sender, + "&b&lPlaceholderAPI &7(&f" + description.getVersion() + "&7)", + "&7Author: &f" + description.getAuthors(), + "&7PAPI Commands: &b/papi &fhelp", + "&7eCloud Commands&8: &b/papi &fecloud"); + } } diff --git a/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java b/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java index 21df3ab..ebef47a 100644 --- a/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java +++ b/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java @@ -29,61 +29,61 @@ import org.jetbrains.annotations.NotNull; /** * This event indicates that a single {@link PlaceholderExpansion PlaceholderExpansion} has * been registered in PlaceholderAPI. - * + * *

To know when all Expansions have been registered, use the * {@link me.clip.placeholderapi.events.ExpansionsLoadedEvent ExpansionsLoadedEvent} instead. */ public final class ExpansionRegisterEvent extends Event implements Cancellable { - @NotNull - private static final HandlerList HANDLERS = new HandlerList(); - @NotNull - private final PlaceholderExpansion expansion; - private boolean cancelled; + @NotNull + private static final HandlerList HANDLERS = new HandlerList(); + @NotNull + private final PlaceholderExpansion expansion; + private boolean cancelled; - public ExpansionRegisterEvent(@NotNull final PlaceholderExpansion expansion) { - this.expansion = expansion; - } + public ExpansionRegisterEvent(@NotNull final PlaceholderExpansion expansion) { + this.expansion = expansion; + } - @NotNull - public static HandlerList getHandlerList() { - return HANDLERS; - } - - /** - * The {@link PlaceholderExpansion PlaceholderExpansion} that was registered in PlaceholderAPI. - *
The PlaceholderExpansion will be available for use when the event - * {@link #isCancelled() was not cancelled}! - * - * @return Current instance of the registered {@link PlaceholderExpansion PlaceholderExpansion} - */ - @NotNull - public PlaceholderExpansion getExpansion() { - return expansion; - } + @NotNull + public static HandlerList getHandlerList() { + return HANDLERS; + } - /** - * Indicates if this event was cancelled or not. - *
A cancelled Event will result in the {@link #getExpansion() PlaceholderExpansion} NOT - * being added to PlaceholderAPI's internal list and will therefore be considered not registered - * anymore. - * - * @return Whether the event has been cancelled or not. - */ - @Override - public boolean isCancelled() { - return cancelled; - } + /** + * The {@link PlaceholderExpansion PlaceholderExpansion} that was registered in PlaceholderAPI. + *
The PlaceholderExpansion will be available for use when the event + * {@link #isCancelled() was not cancelled}! + * + * @return Current instance of the registered {@link PlaceholderExpansion PlaceholderExpansion} + */ + @NotNull + public PlaceholderExpansion getExpansion() { + return expansion; + } - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } + /** + * Indicates if this event was cancelled or not. + *
A cancelled Event will result in the {@link #getExpansion() PlaceholderExpansion} NOT + * being added to PlaceholderAPI's internal list and will therefore be considered not registered + * anymore. + * + * @return Whether the event has been cancelled or not. + */ + @Override + public boolean isCancelled() { + return cancelled; + } - @NotNull - @Override - public HandlerList getHandlers() { - return HANDLERS; - } + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @NotNull + @Override + public HandlerList getHandlers() { + return HANDLERS; + } } diff --git a/src/main/java/me/clip/placeholderapi/events/ExpansionUnregisterEvent.java b/src/main/java/me/clip/placeholderapi/events/ExpansionUnregisterEvent.java index e899b60..3e04410 100644 --- a/src/main/java/me/clip/placeholderapi/events/ExpansionUnregisterEvent.java +++ b/src/main/java/me/clip/placeholderapi/events/ExpansionUnregisterEvent.java @@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull; /** * This event indicates that a {@link PlaceholderExpansion PlaceholderExpansion} has been * unregistered by PlaceholderAPI. - * + * *

Note that this event is triggered before the PlaceholderExpansion is completely * removed. *
This includes removing any Listeners, stopping active tasks and clearing the cache of @@ -36,35 +36,35 @@ import org.jetbrains.annotations.NotNull; */ public final class ExpansionUnregisterEvent extends Event { - @NotNull - private static final HandlerList HANDLERS = new HandlerList(); - - @NotNull - private final PlaceholderExpansion expansion; + @NotNull + private static final HandlerList HANDLERS = new HandlerList(); - public ExpansionUnregisterEvent(@NotNull final PlaceholderExpansion expansion) { - this.expansion = expansion; - } + @NotNull + private final PlaceholderExpansion expansion; - @NotNull - public static HandlerList getHandlerList() { - return HANDLERS; - } - - /** - * The {@link PlaceholderExpansion PlaceholderExpansion} that was unregistered. - * - * @return The {@link PlaceholderExpansion PlaceholderExpansion} instance. - */ - @NotNull - public PlaceholderExpansion getExpansion() { - return expansion; - } + public ExpansionUnregisterEvent(@NotNull final PlaceholderExpansion expansion) { + this.expansion = expansion; + } - @NotNull - @Override - public HandlerList getHandlers() { - return HANDLERS; - } + @NotNull + public static HandlerList getHandlerList() { + return HANDLERS; + } + + /** + * The {@link PlaceholderExpansion PlaceholderExpansion} that was unregistered. + * + * @return The {@link PlaceholderExpansion PlaceholderExpansion} instance. + */ + @NotNull + public PlaceholderExpansion getExpansion() { + return expansion; + } + + @NotNull + @Override + public HandlerList getHandlers() { + return HANDLERS; + } } diff --git a/src/main/java/me/clip/placeholderapi/events/ExpansionsLoadedEvent.java b/src/main/java/me/clip/placeholderapi/events/ExpansionsLoadedEvent.java index 872d275..6b60e25 100644 --- a/src/main/java/me/clip/placeholderapi/events/ExpansionsLoadedEvent.java +++ b/src/main/java/me/clip/placeholderapi/events/ExpansionsLoadedEvent.java @@ -23,6 +23,7 @@ package me.clip.placeholderapi.events; import java.util.Collections; import java.util.List; + import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; @@ -32,14 +33,14 @@ import org.jetbrains.annotations.NotNull; * This event indicated that all {@link PlaceholderExpansion PlaceholderExpansions} have * been registered in PlaceholderAPI and can now be used. *
This even will also be triggered whenever PlaceholderAPI gets reloaded. - * + * *

All PlaceholderExpansions, except for those loaded by plugins, are loaded * after Spigot triggered its ServerLoadEvent (1.13+), or after PlaceholderAPI has been enabled. */ public class ExpansionsLoadedEvent extends Event { - + private final List expansions; - + public ExpansionsLoadedEvent(List expansions) { this.expansions = Collections.unmodifiableList(expansions); } @@ -47,16 +48,16 @@ public class ExpansionsLoadedEvent extends Event { /** * Returns a unmodifiable list of {@link PlaceholderExpansion PlaceholderExpansions} that * have been registered by PlaceholderAPI. - * + * *

This list does not include manually registered PlaceholderExpansions. - * + * * @return List of {@link PlaceholderExpansion registered PlaceholderExpansions}. */ @NotNull - public final List getExpansions(){ + public final List getExpansions() { return expansions; } - + @NotNull private static final HandlerList HANDLERS = new HandlerList(); diff --git a/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java b/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java index e0a8ce5..9d9a888 100644 --- a/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java +++ b/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java @@ -31,40 +31,40 @@ import org.jetbrains.annotations.NotNull; @Deprecated public final class PlaceholderHookUnloadEvent extends Event { - @NotNull - private static final HandlerList HANDLERS = new HandlerList(); + @NotNull + private static final HandlerList HANDLERS = new HandlerList(); - @NotNull - private final String plugin; - @NotNull - private final PlaceholderHook placeholderHook; + @NotNull + private final String plugin; + @NotNull + private final PlaceholderHook placeholderHook; - public PlaceholderHookUnloadEvent(@NotNull final String plugin, - @NotNull final PlaceholderHook placeholderHook) { - this.plugin = plugin; - this.placeholderHook = placeholderHook; - } + public PlaceholderHookUnloadEvent(@NotNull final String plugin, + @NotNull final PlaceholderHook placeholderHook) { + this.plugin = plugin; + this.placeholderHook = placeholderHook; + } - @NotNull - public static HandlerList getHandlerList() { - return HANDLERS; - } + @NotNull + public static HandlerList getHandlerList() { + return HANDLERS; + } - @NotNull - public String getHookName() { - return plugin; - } + @NotNull + public String getHookName() { + return plugin; + } - @NotNull - public PlaceholderHook getHook() { - return placeholderHook; - } + @NotNull + public PlaceholderHook getHook() { + return placeholderHook; + } - @NotNull - @Override - public HandlerList getHandlers() { - return HANDLERS; - } + @NotNull + @Override + public HandlerList getHandlers() { + return HANDLERS; + } } diff --git a/src/main/java/me/clip/placeholderapi/expansion/Version.java b/src/main/java/me/clip/placeholderapi/expansion/Version.java index d9ac195..fa1d15d 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Version.java +++ b/src/main/java/me/clip/placeholderapi/expansion/Version.java @@ -23,24 +23,24 @@ package me.clip.placeholderapi.expansion; @Deprecated public final class Version { - private final boolean isSpigot; - private final String version; + private final boolean isSpigot; + private final String version; - public Version(String version, boolean isSpigot) { - this.version = version; - this.isSpigot = isSpigot; - } + public Version(String version, boolean isSpigot) { + this.version = version; + this.isSpigot = isSpigot; + } - public String getVersion() { - return version == null ? "unknown" : version; - } + public String getVersion() { + return version == null ? "unknown" : version; + } - public boolean isSpigot() { - return isSpigot; - } + public boolean isSpigot() { + return isSpigot; + } - public boolean compareTo(String version) { - return getVersion().equalsIgnoreCase(version); - } + public boolean compareTo(String version) { + return getVersion().equalsIgnoreCase(version); + } } diff --git a/src/main/java/me/clip/placeholderapi/expansion/cloud/CloudExpansion.java b/src/main/java/me/clip/placeholderapi/expansion/cloud/CloudExpansion.java index f5d158f..08a5c46 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/cloud/CloudExpansion.java +++ b/src/main/java/me/clip/placeholderapi/expansion/cloud/CloudExpansion.java @@ -23,180 +23,181 @@ package me.clip.placeholderapi.expansion.cloud; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; + import me.clip.placeholderapi.util.TimeUtil; public class CloudExpansion { - private String name, - author, - latest_version, - description, - source_url, - dependency_url; + private String name, + author, + latest_version, + description, + source_url, + dependency_url; - private boolean hasExpansion, - shouldUpdate, - verified; + private boolean hasExpansion, + shouldUpdate, + verified; - private long last_update, - ratings_count; + private long last_update, + ratings_count; - private double average_rating; + private double average_rating; - private List placeholders; + private List placeholders; - private List versions; + private List versions; - public CloudExpansion() { - } - - public String getTimeSinceLastUpdate() { - int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - getLastUpdate()); - return TimeUtil.getTime(time); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - - public Version getVersion() { - return getLatestVersion() == null ? null : getVersion(getLatestVersion()); - } - - public Version getVersion(String version) { - return versions == null ? null : versions.stream() - .filter(v -> v.getVersion().equals(version)) - .findFirst() - .orElse(null); - } - - public List getAvailableVersions() { - return versions.stream().map(Version::getVersion).collect(Collectors.toList()); - } - - public String getLatestVersion() { - return latest_version; - } - - public void setLatestVersion(String latest_version) { - this.latest_version = latest_version; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getSourceUrl() { - return source_url; - } - - public void setSourceUrl(String source_url) { - this.source_url = source_url; - } - - public String getDependencyUrl() { - return dependency_url; - } - - public void setDependencyUrl(String dependency_url) { - this.dependency_url = dependency_url; - } - - public boolean hasExpansion() { - return hasExpansion; - } - - public void setHasExpansion(boolean hasExpansion) { - this.hasExpansion = hasExpansion; - } - - public boolean shouldUpdate() { - return shouldUpdate; - } - - public void setShouldUpdate(boolean shouldUpdate) { - this.shouldUpdate = shouldUpdate; - } - - public boolean isVerified() { - return verified; - } - - public long getLastUpdate() { - return last_update; - } - - public void setLastUpdate(long last_update) { - this.last_update = last_update; - } - - public long getRatingsCount() { - return ratings_count; - } - - public double getAverage_rating() { - return average_rating; - } - - public List getPlaceholders() { - return placeholders; - } - - public void setPlaceholders(List placeholders) { - this.placeholders = placeholders; - } - - public List getVersions() { - return versions; - } - - public void setVersions(List versions) { - this.versions = versions; - } - - public static class Version { - - private String url, version, release_notes; - - public String getUrl() { - return url; + public CloudExpansion() { } - public void setUrl(String url) { - this.url = url; + public String getTimeSinceLastUpdate() { + int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - getLastUpdate()); + return TimeUtil.getTime(time); } - public String getVersion() { - return version; + public String getName() { + return name; } - public void setVersion(String version) { - this.version = version; + public void setName(String name) { + this.name = name; } - public String getReleaseNotes() { - return release_notes; + public String getAuthor() { + return author; } - public void setReleaseNotes(String release_notes) { - this.release_notes = release_notes; + public void setAuthor(String author) { + this.author = author; + } + + public Version getVersion() { + return getLatestVersion() == null ? null : getVersion(getLatestVersion()); + } + + public Version getVersion(String version) { + return versions == null ? null : versions.stream() + .filter(v -> v.getVersion().equals(version)) + .findFirst() + .orElse(null); + } + + public List getAvailableVersions() { + return versions.stream().map(Version::getVersion).collect(Collectors.toList()); + } + + public String getLatestVersion() { + return latest_version; + } + + public void setLatestVersion(String latest_version) { + this.latest_version = latest_version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getSourceUrl() { + return source_url; + } + + public void setSourceUrl(String source_url) { + this.source_url = source_url; + } + + public String getDependencyUrl() { + return dependency_url; + } + + public void setDependencyUrl(String dependency_url) { + this.dependency_url = dependency_url; + } + + public boolean hasExpansion() { + return hasExpansion; + } + + public void setHasExpansion(boolean hasExpansion) { + this.hasExpansion = hasExpansion; + } + + public boolean shouldUpdate() { + return shouldUpdate; + } + + public void setShouldUpdate(boolean shouldUpdate) { + this.shouldUpdate = shouldUpdate; + } + + public boolean isVerified() { + return verified; + } + + public long getLastUpdate() { + return last_update; + } + + public void setLastUpdate(long last_update) { + this.last_update = last_update; + } + + public long getRatingsCount() { + return ratings_count; + } + + public double getAverage_rating() { + return average_rating; + } + + public List getPlaceholders() { + return placeholders; + } + + public void setPlaceholders(List placeholders) { + this.placeholders = placeholders; + } + + public List getVersions() { + return versions; + } + + public void setVersions(List versions) { + this.versions = versions; + } + + public static class Version { + + private String url, version, release_notes; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getReleaseNotes() { + return release_notes; + } + + public void setReleaseNotes(String release_notes) { + this.release_notes = release_notes; + } } - } } diff --git a/src/main/java/me/clip/placeholderapi/expansion/manager/CloudExpansionManager.java b/src/main/java/me/clip/placeholderapi/expansion/manager/CloudExpansionManager.java index 89c1d81..d915867 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/manager/CloudExpansionManager.java +++ b/src/main/java/me/clip/placeholderapi/expansion/manager/CloudExpansionManager.java @@ -25,6 +25,7 @@ import com.google.common.io.Resources; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -50,6 +51,7 @@ import java.util.function.Function; import java.util.logging.Level; import java.util.stream.Collector; import java.util.stream.Collectors; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import me.clip.placeholderapi.expansion.cloud.CloudExpansion; @@ -59,218 +61,218 @@ import org.jetbrains.annotations.Unmodifiable; public final class CloudExpansionManager { - @NotNull - private static final String API_URL = "http://api.extendedclip.com/v2/"; + @NotNull + private static final String API_URL = "http://api.extendedclip.com/v2/"; - @NotNull - private static final Gson GSON = new Gson(); - @NotNull - private static final Type TYPE = new TypeToken>() {}.getType(); + @NotNull + private static final Gson GSON = new Gson(); + @NotNull + private static final Type TYPE = new TypeToken>() {}.getType(); - @NotNull - private final Collector> INDEXED_NAME_COLLECTOR = Collectors - .toMap(CloudExpansionManager::toIndexName, Function.identity()); + @NotNull + private final Collector> INDEXED_NAME_COLLECTOR = Collectors + .toMap(CloudExpansionManager::toIndexName, Function.identity()); - @NotNull - private final PlaceholderAPIPlugin plugin; + @NotNull + private final PlaceholderAPIPlugin plugin; - @NotNull - private final Map cache = new HashMap<>(); - @NotNull - private final Map> await = new ConcurrentHashMap<>(); + @NotNull + private final Map cache = new HashMap<>(); + @NotNull + private final Map> await = new ConcurrentHashMap<>(); - private final ExecutorService ASYNC_EXECUTOR = - Executors.newCachedThreadPool( - new ThreadFactoryBuilder().setNameFormat("placeholderapi-io-#%1$d").build()); + private final ExecutorService ASYNC_EXECUTOR = + Executors.newCachedThreadPool( + new ThreadFactoryBuilder().setNameFormat("placeholderapi-io-#%1$d").build()); - public CloudExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) { - this.plugin = plugin; - } - - @NotNull - private static String toIndexName(@NotNull final String name) { - return name.toLowerCase(Locale.ROOT).replace(' ', '_'); - } - - @NotNull - private static String toIndexName(@NotNull final CloudExpansion expansion) { - return toIndexName(expansion.getName()); - } - - public void load() { - clean(); - fetch(); - } - - public void kill() { - clean(); - } - - @NotNull - @Unmodifiable - public Map getCloudExpansions() { - return ImmutableMap.copyOf(cache); - } - - @NotNull - @Unmodifiable - public Map getCloudExpansionsInstalled() { - if (cache.isEmpty()) { - return Collections.emptyMap(); + public CloudExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) { + this.plugin = plugin; } - return cache.values() - .stream() - .filter(CloudExpansion::hasExpansion) - .collect(INDEXED_NAME_COLLECTOR); - } - - @NotNull - @Unmodifiable - public Map getCloudExpansionsByAuthor(@NotNull final String author) { - if (cache.isEmpty()) { - return Collections.emptyMap(); + @NotNull + private static String toIndexName(@NotNull final String name) { + return name.toLowerCase(Locale.ROOT).replace(' ', '_'); } - return cache.values() - .stream() - .filter(expansion -> author.equalsIgnoreCase(expansion.getAuthor())) - .collect(INDEXED_NAME_COLLECTOR); - } + @NotNull + private static String toIndexName(@NotNull final CloudExpansion expansion) { + return toIndexName(expansion.getName()); + } - @NotNull - @Unmodifiable - public Set getCloudExpansionAuthors() { - return cache.values().stream().map(CloudExpansion::getAuthor).collect(Collectors.toSet()); - } + public void load() { + clean(); + fetch(); + } - public int getCloudExpansionAuthorCount() { - return getCloudExpansionAuthors().size(); - } + public void kill() { + clean(); + } - public int getCloudUpdateCount() { - return ((int) plugin.getLocalExpansionManager() - .getExpansions() - .stream() - .filter(expansion -> findCloudExpansionByName(expansion.getName()) - .map(CloudExpansion::shouldUpdate).orElse(false)) - .count()); - } + @NotNull + @Unmodifiable + public Map getCloudExpansions() { + return ImmutableMap.copyOf(cache); + } - @NotNull - public Optional findCloudExpansionByName(@NotNull final String name) { - return Optional.ofNullable(cache.get(toIndexName(name))); - } + @NotNull + @Unmodifiable + public Map getCloudExpansionsInstalled() { + if (cache.isEmpty()) { + return Collections.emptyMap(); + } - public void clean() { - cache.clear(); + return cache.values() + .stream() + .filter(CloudExpansion::hasExpansion) + .collect(INDEXED_NAME_COLLECTOR); + } - await.values().forEach(future -> future.cancel(true)); - await.clear(); - } + @NotNull + @Unmodifiable + public Map getCloudExpansionsByAuthor(@NotNull final String author) { + if (cache.isEmpty()) { + return Collections.emptyMap(); + } - public void fetch() { - plugin.getLogger().info("Fetching available expansion information..."); + return cache.values() + .stream() + .filter(expansion -> author.equalsIgnoreCase(expansion.getAuthor())) + .collect(INDEXED_NAME_COLLECTOR); + } - ASYNC_EXECUTOR.submit( - () -> { - // a defence tactic! use ConcurrentHashMap instead of normal HashMap - Map values = new ConcurrentHashMap<>(); - try { - //noinspection UnstableApiUsage - String json = Resources.toString(new URL(API_URL), StandardCharsets.UTF_8); - values.putAll(GSON.fromJson(json, TYPE)); + @NotNull + @Unmodifiable + public Set getCloudExpansionAuthors() { + return cache.values().stream().map(CloudExpansion::getAuthor).collect(Collectors.toSet()); + } - List toRemove = new ArrayList<>(); + public int getCloudExpansionAuthorCount() { + return getCloudExpansionAuthors().size(); + } - for (Map.Entry entry : values.entrySet()) { - CloudExpansion expansion = entry.getValue(); - if (expansion.getLatestVersion() == null - || expansion.getVersion(expansion.getLatestVersion()) == null) { - toRemove.add(entry.getKey()); - } - } + public int getCloudUpdateCount() { + return ((int) plugin.getLocalExpansionManager() + .getExpansions() + .stream() + .filter(expansion -> findCloudExpansionByName(expansion.getName()) + .map(CloudExpansion::shouldUpdate).orElse(false)) + .count()); + } - for (String name : toRemove) { - values.remove(name); - } - } catch (Throwable e) { - // ugly swallowing of every throwable, but we have to be defensive - plugin.getLogger().log(Level.WARNING, "Failed to download expansion information", e); - } + @NotNull + public Optional findCloudExpansionByName(@NotNull final String name) { + return Optional.ofNullable(cache.get(toIndexName(name))); + } - // loop through what's left on the main thread - plugin - .getScheduler() - .runTask( - () -> { + public void clean() { + cache.clear(); + + await.values().forEach(future -> future.cancel(true)); + await.clear(); + } + + public void fetch() { + plugin.getLogger().info("Fetching available expansion information..."); + + ASYNC_EXECUTOR.submit( + () -> { + // a defence tactic! use ConcurrentHashMap instead of normal HashMap + Map values = new ConcurrentHashMap<>(); try { - for (Map.Entry entry : values.entrySet()) { - String name = entry.getKey(); - CloudExpansion expansion = entry.getValue(); + //noinspection UnstableApiUsage + String json = Resources.toString(new URL(API_URL), StandardCharsets.UTF_8); + values.putAll(GSON.fromJson(json, TYPE)); - expansion.setName(name); + List toRemove = new ArrayList<>(); - Optional localOpt = - plugin.getLocalExpansionManager().findExpansionByName(name); - if (localOpt.isPresent()) { - PlaceholderExpansion local = localOpt.get(); - if (local.isRegistered()) { - expansion.setHasExpansion(true); - expansion.setShouldUpdate( - !local.getVersion().equalsIgnoreCase(expansion.getLatestVersion())); - } + for (Map.Entry entry : values.entrySet()) { + CloudExpansion expansion = entry.getValue(); + if (expansion.getLatestVersion() == null + || expansion.getVersion(expansion.getLatestVersion()) == null) { + toRemove.add(entry.getKey()); + } } - cache.put(toIndexName(expansion), expansion); - } + for (String name : toRemove) { + values.remove(name); + } } catch (Throwable e) { - // ugly swallowing of every throwable, but we have to be defensive - plugin - .getLogger() - .log(Level.WARNING, "Failed to download expansion information", e); + // ugly swallowing of every throwable, but we have to be defensive + plugin.getLogger().log(Level.WARNING, "Failed to download expansion information", e); } - }); - }); - } - public boolean isDownloading(@NotNull final CloudExpansion expansion) { - return await.containsKey(toIndexName(expansion)); - } + // loop through what's left on the main thread + plugin + .getScheduler() + .runTask( + () -> { + try { + for (Map.Entry entry : values.entrySet()) { + String name = entry.getKey(); + CloudExpansion expansion = entry.getValue(); - @NotNull - public CompletableFuture downloadExpansion(@NotNull final CloudExpansion expansion, - @NotNull final CloudExpansion.Version version) { - final CompletableFuture previous = await.get(toIndexName(expansion)); - if (previous != null) { - return previous; + expansion.setName(name); + + Optional localOpt = + plugin.getLocalExpansionManager().findExpansionByName(name); + if (localOpt.isPresent()) { + PlaceholderExpansion local = localOpt.get(); + if (local.isRegistered()) { + expansion.setHasExpansion(true); + expansion.setShouldUpdate( + !local.getVersion().equalsIgnoreCase(expansion.getLatestVersion())); + } + } + + cache.put(toIndexName(expansion), expansion); + } + } catch (Throwable e) { + // ugly swallowing of every throwable, but we have to be defensive + plugin + .getLogger() + .log(Level.WARNING, "Failed to download expansion information", e); + } + }); + }); } - final File file = new File(plugin.getLocalExpansionManager().getExpansionsFolder(), - "Expansion-" + toIndexName(expansion) + ".jar"); + public boolean isDownloading(@NotNull final CloudExpansion expansion) { + return await.containsKey(toIndexName(expansion)); + } - final CompletableFuture download = CompletableFuture.supplyAsync(() -> { - try (final ReadableByteChannel source = Channels.newChannel(new URL(version.getUrl()) - .openStream()); final FileOutputStream target = new FileOutputStream(file)) { - target.getChannel().transferFrom(source, 0, Long.MAX_VALUE); - } catch (final IOException ex) { - throw new CompletionException(ex); - } - return file; - }, ASYNC_EXECUTOR); + @NotNull + public CompletableFuture downloadExpansion(@NotNull final CloudExpansion expansion, + @NotNull final CloudExpansion.Version version) { + final CompletableFuture previous = await.get(toIndexName(expansion)); + if (previous != null) { + return previous; + } - download.whenCompleteAsync((value, exception) -> { - await.remove(toIndexName(expansion)); + final File file = new File(plugin.getLocalExpansionManager().getExpansionsFolder(), + "Expansion-" + toIndexName(expansion) + ".jar"); - if (exception != null) { - Msg.severe("Failed to download %s:%s", exception, expansion.getName(), expansion.getVersion()); - } - }, ASYNC_EXECUTOR); + final CompletableFuture download = CompletableFuture.supplyAsync(() -> { + try (final ReadableByteChannel source = Channels.newChannel(new URL(version.getUrl()) + .openStream()); final FileOutputStream target = new FileOutputStream(file)) { + target.getChannel().transferFrom(source, 0, Long.MAX_VALUE); + } catch (final IOException ex) { + throw new CompletionException(ex); + } + return file; + }, ASYNC_EXECUTOR); - await.put(toIndexName(expansion), download); + download.whenCompleteAsync((value, exception) -> { + await.remove(toIndexName(expansion)); - return download; - } + if (exception != null) { + Msg.severe("Failed to download %s:%s", exception, expansion.getName(), expansion.getVersion()); + } + }, ASYNC_EXECUTOR); + + await.put(toIndexName(expansion), download); + + return download; + } } diff --git a/src/main/java/me/clip/placeholderapi/expansion/manager/LocalExpansionManager.java b/src/main/java/me/clip/placeholderapi/expansion/manager/LocalExpansionManager.java index 6128a64..f321a3e 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/manager/LocalExpansionManager.java +++ b/src/main/java/me/clip/placeholderapi/expansion/manager/LocalExpansionManager.java @@ -22,6 +22,7 @@ package me.clip.placeholderapi.expansion.manager; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; + import java.io.File; import java.lang.reflect.Modifier; import java.util.Arrays; @@ -38,6 +39,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.stream.Collectors; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.events.ExpansionRegisterEvent; import me.clip.placeholderapi.events.ExpansionUnregisterEvent; @@ -68,428 +70,429 @@ import org.jetbrains.annotations.Unmodifiable; public final class LocalExpansionManager implements Listener { - @NotNull - private static final String EXPANSIONS_FOLDER_NAME = "expansions"; + @NotNull + private static final String EXPANSIONS_FOLDER_NAME = "expansions"; - @NotNull - private static final Set ABSTRACT_EXPANSION_METHODS = Arrays.stream(PlaceholderExpansion.class.getDeclaredMethods()) - .filter(method -> Modifier.isAbstract(method.getModifiers())) - .map(method -> new MethodSignature(method.getName(), method.getParameterTypes())) - .collect(Collectors.toSet()); + @NotNull + private static final Set ABSTRACT_EXPANSION_METHODS = Arrays.stream(PlaceholderExpansion.class.getDeclaredMethods()) + .filter(method -> Modifier.isAbstract(method.getModifiers())) + .map(method -> new MethodSignature(method.getName(), method.getParameterTypes())) + .collect(Collectors.toSet()); - @NotNull - private final File folder; - @NotNull - private final PlaceholderAPIPlugin plugin; + @NotNull + private final File folder; + @NotNull + private final PlaceholderAPIPlugin plugin; - @NotNull - private final Map expansions = new ConcurrentHashMap<>(); - private final ReentrantLock expansionsLock = new ReentrantLock(); + @NotNull + private final Map expansions = new ConcurrentHashMap<>(); + private final ReentrantLock expansionsLock = new ReentrantLock(); - public LocalExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) { - this.plugin = plugin; - this.folder = new File(plugin.getDataFolder(), EXPANSIONS_FOLDER_NAME); + public LocalExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) { + this.plugin = plugin; + this.folder = new File(plugin.getDataFolder(), EXPANSIONS_FOLDER_NAME); - if (!this.folder.exists() && !folder.mkdirs()) { - Msg.warn("Failed to create expansions folder!"); - } - } - - public void load(@NotNull final CommandSender sender) { - registerAll(sender); - } - - public void kill() { - unregisterAll(); - } - - - @NotNull - public File getExpansionsFolder() { - return folder; - } - - @NotNull - @Unmodifiable - public Collection getIdentifiers() { - expansionsLock.lock(); - try { - return ImmutableSet.copyOf(expansions.keySet()); - } finally { - expansionsLock.unlock(); - } - } - - @NotNull - @Unmodifiable - public Collection getExpansions() { - expansionsLock.lock(); - try { - return ImmutableSet.copyOf(expansions.values()); - } finally { - expansionsLock.unlock(); - } - } - - @Nullable - public PlaceholderExpansion getExpansion(@NotNull final String identifier) { - expansionsLock.lock(); - try { - return expansions.get(identifier.toLowerCase(Locale.ROOT)); - } finally { - expansionsLock.unlock(); - } - } - - @NotNull - public Optional findExpansionByName(@NotNull final String name) { - expansionsLock.lock(); - try { - PlaceholderExpansion bestMatch = null; - for (Map.Entry entry : expansions.entrySet()) { - PlaceholderExpansion expansion = entry.getValue(); - if (expansion.getName().equalsIgnoreCase(name)) { - bestMatch = expansion; - break; + if (!this.folder.exists() && !folder.mkdirs()) { + Msg.warn("Failed to create expansions folder!"); } - } - return Optional.ofNullable(bestMatch); - } finally { - expansionsLock.unlock(); } - } - @NotNull - public Optional findExpansionByIdentifier( - @NotNull final String identifier) { - return Optional.ofNullable(getExpansion(identifier)); - } + public void load(@NotNull final CommandSender sender) { + registerAll(sender); + } + + public void kill() { + unregisterAll(); + } - public Optional register( - @NotNull final Class clazz) { - try { - final PlaceholderExpansion expansion = createExpansionInstance(clazz); - - if(expansion == null){ - return Optional.empty(); - } - - Objects.requireNonNull(expansion.getAuthor(), "The expansion author is null!"); - Objects.requireNonNull(expansion.getIdentifier(), "The expansion identifier is null!"); - Objects.requireNonNull(expansion.getVersion(), "The expansion version is null!"); - - if (expansion.getRequiredPlugin() != null && !expansion.getRequiredPlugin().isEmpty()) { - if (!Bukkit.getPluginManager().isPluginEnabled(expansion.getRequiredPlugin())) { - Msg.warn("Cannot load expansion %s due to a missing plugin: %s", expansion.getIdentifier(), - expansion.getRequiredPlugin()); - return Optional.empty(); + @NotNull + public File getExpansionsFolder() { + return folder; + } + + @NotNull + @Unmodifiable + public Collection getIdentifiers() { + expansionsLock.lock(); + try { + return ImmutableSet.copyOf(expansions.keySet()); + } finally { + expansionsLock.unlock(); } - } - - expansion.setExpansionType(PlaceholderExpansion.Type.EXTERNAL); - - if (!expansion.register()) { - Msg.warn("Cannot load expansion %s due to an unknown issue.", expansion.getIdentifier()); - return Optional.empty(); - } - - return Optional.of(expansion); - } catch (LinkageError | NullPointerException ex) { - final String reason; - - if (ex instanceof LinkageError) { - reason = " (Is a dependency missing?)"; - } else { - reason = " - One of its properties is null which is not allowed!"; - } - - Msg.severe("Failed to load expansion class %s%s", ex, clazz.getSimpleName(), reason); } - return Optional.empty(); - } - - /** - * Attempt to register a {@link PlaceholderExpansion} - * @param expansion the expansion to register - * @return if the expansion was registered - */ - @ApiStatus.Internal - public boolean register(@NotNull final PlaceholderExpansion expansion) { - final String identifier = expansion.getIdentifier().toLowerCase(Locale.ROOT); - - if (!expansion.canRegister()) { - return false; + @NotNull + @Unmodifiable + public Collection getExpansions() { + expansionsLock.lock(); + try { + return ImmutableSet.copyOf(expansions.values()); + } finally { + expansionsLock.unlock(); + } } - // Avoid loading two external expansions with the same identifier - if (expansion.getExpansionType() == PlaceholderExpansion.Type.EXTERNAL && expansions.containsKey(identifier)) { - Msg.warn("Failed to load external expansion %s. Identifier is already in use.", expansion.getIdentifier()); - return false; + @Nullable + public PlaceholderExpansion getExpansion(@NotNull final String identifier) { + expansionsLock.lock(); + try { + return expansions.get(identifier.toLowerCase(Locale.ROOT)); + } finally { + expansionsLock.unlock(); + } } - if (expansion instanceof Configurable) { - Map defaults = ((Configurable) expansion).getDefaults(); - String pre = "expansions." + identifier + "."; - FileConfiguration cfg = plugin.getConfig(); - boolean save = false; - - if (defaults != null) { - for (Map.Entry entries : defaults.entrySet()) { - if (entries.getKey() == null || entries.getKey().isEmpty()) { - continue; - } - - if (entries.getValue() == null) { - if (cfg.contains(pre + entries.getKey())) { - save = true; - cfg.set(pre + entries.getKey(), null); + @NotNull + public Optional findExpansionByName(@NotNull final String name) { + expansionsLock.lock(); + try { + PlaceholderExpansion bestMatch = null; + for (Map.Entry entry : expansions.entrySet()) { + PlaceholderExpansion expansion = entry.getValue(); + if (expansion.getName().equalsIgnoreCase(name)) { + bestMatch = expansion; + break; + } } - } else { - if (!cfg.contains(pre + entries.getKey())) { - save = true; - cfg.set(pre + entries.getKey(), entries.getValue()); + return Optional.ofNullable(bestMatch); + } finally { + expansionsLock.unlock(); + } + } + + @NotNull + public Optional findExpansionByIdentifier( + @NotNull final String identifier) { + return Optional.ofNullable(getExpansion(identifier)); + } + + + public Optional register( + @NotNull final Class clazz) { + try { + final PlaceholderExpansion expansion = createExpansionInstance(clazz); + + if (expansion == null) { + return Optional.empty(); } - } - } - } - if (save) { - plugin.saveConfig(); - plugin.reloadConfig(); - } - } + Objects.requireNonNull(expansion.getAuthor(), "The expansion author is null!"); + Objects.requireNonNull(expansion.getIdentifier(), "The expansion identifier is null!"); + Objects.requireNonNull(expansion.getVersion(), "The expansion version is null!"); - if (expansion instanceof VersionSpecific) { - VersionSpecific nms = (VersionSpecific) expansion; - if (!nms.isCompatibleWith(PlaceholderAPIPlugin.getServerVersion())) { - Msg.warn("Your server version is incompatible with expansion %s %s", - expansion.getIdentifier(), expansion.getVersion()); - return false; - } - } + if (expansion.getRequiredPlugin() != null && !expansion.getRequiredPlugin().isEmpty()) { + if (!Bukkit.getPluginManager().isPluginEnabled(expansion.getRequiredPlugin())) { + Msg.warn("Cannot load expansion %s due to a missing plugin: %s", expansion.getIdentifier(), + expansion.getRequiredPlugin()); + return Optional.empty(); + } + } - final PlaceholderExpansion removed = getExpansion(identifier); - if (removed != null && !removed.unregister()) { - return false; - } + expansion.setExpansionType(PlaceholderExpansion.Type.EXTERNAL); - final ExpansionRegisterEvent event = new ExpansionRegisterEvent(expansion); - Bukkit.getPluginManager().callEvent(event); + if (!expansion.register()) { + Msg.warn("Cannot load expansion %s due to an unknown issue.", expansion.getIdentifier()); + return Optional.empty(); + } - if (event.isCancelled()) { - return false; - } + return Optional.of(expansion); + } catch (LinkageError | NullPointerException ex) { + final String reason; - expansionsLock.lock(); - try { - expansions.put(identifier, expansion); - } finally { - expansionsLock.unlock(); - } + if (ex instanceof LinkageError) { + reason = " (Is a dependency missing?)"; + } else { + reason = " - One of its properties is null which is not allowed!"; + } - if (expansion instanceof Listener) { - Bukkit.getPluginManager().registerEvents(((Listener) expansion), plugin); - } - - Msg.info( - "Successfully registered %s expansion: %s [%s]", - expansion.getExpansionType().name().toLowerCase(), - expansion.getIdentifier(), - expansion.getVersion() - ); - - if (expansion instanceof Taskable) { - ((Taskable) expansion).start(); - } - - // Check eCloud for updates only if the expansion is external - if (plugin.getPlaceholderAPIConfig().isCloudEnabled() && expansion.getExpansionType() == PlaceholderExpansion.Type.EXTERNAL) { - final Optional cloudExpansionOptional = plugin.getCloudExpansionManager().findCloudExpansionByName(identifier); - if (cloudExpansionOptional.isPresent()) { - CloudExpansion cloudExpansion = cloudExpansionOptional.get(); - cloudExpansion.setHasExpansion(true); - cloudExpansion.setShouldUpdate(!cloudExpansion.getLatestVersion().equals(expansion.getVersion())); - } - } - - return true; - } - - @ApiStatus.Internal - public boolean unregister(@NotNull final PlaceholderExpansion expansion) { - if (expansions.remove(expansion.getIdentifier().toLowerCase(Locale.ROOT)) == null) { - return false; - } - - Bukkit.getPluginManager().callEvent(new ExpansionUnregisterEvent(expansion)); - - if (expansion instanceof Listener) { - HandlerList.unregisterAll((Listener) expansion); - } - - if (expansion instanceof Taskable) { - ((Taskable) expansion).stop(); - } - - if (expansion instanceof Cacheable) { - ((Cacheable) expansion).clear(); - } - - if (plugin.getPlaceholderAPIConfig().isCloudEnabled()) { - plugin.getCloudExpansionManager().findCloudExpansionByName(expansion.getName()) - .ifPresent(cloud -> { - cloud.setHasExpansion(false); - cloud.setShouldUpdate(false); - }); - } - - return true; - } - - private void registerAll(@NotNull final CommandSender sender) { - Msg.info("Placeholder expansion registration initializing..."); - - Futures.onMainThread(plugin, findExpansionsOnDisk(), (classes, exception) -> { - if (exception != null) { - Msg.severe("Failed to load class files of expansion.", exception); - return; - } - - final List registered = classes.stream() - .filter(Objects::nonNull) - .map(this::register) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toList()); - - final long needsUpdate = registered.stream() - .map(expansion -> plugin.getCloudExpansionManager().findCloudExpansionByName(expansion.getName()).orElse(null)) - .filter(Objects::nonNull) - .filter(CloudExpansion::shouldUpdate) - .count(); - - StringBuilder message = new StringBuilder(registered.size() == 0 ? "&6" : "&a") - .append(registered.size()) - .append(' ') - .append("placeholder hook(s) registered!"); - - if (needsUpdate > 0) { - message.append(' ') - .append("&6") - .append(needsUpdate) - .append(' ') - .append("placeholder hook(s) have an update available."); - } - - - Msg.msg(sender, message.toString()); - - Bukkit.getPluginManager().callEvent(new ExpansionsLoadedEvent(registered)); - }); - } - - private void unregisterAll() { - for (final PlaceholderExpansion expansion : Sets.newHashSet(expansions.values())) { - if (expansion.persist()) { - continue; - } - - expansion.unregister(); - } - } - - @NotNull - public CompletableFuture<@NotNull List<@Nullable Class>> findExpansionsOnDisk() { - File[] files = folder.listFiles((dir, name) -> name.endsWith(".jar")); - if (files == null) { - return CompletableFuture.completedFuture(Collections.emptyList()); - } - - return Arrays.stream(files) - .map(this::findExpansionInFile) - .collect(Futures.collector()); - } - - @NotNull - public CompletableFuture<@Nullable Class> findExpansionInFile( - @NotNull final File file) { - return CompletableFuture.supplyAsync(() -> { - try { - final Class expansionClass = FileUtil.findClass(file, PlaceholderExpansion.class); - - if (expansionClass == null) { - Msg.severe("Failed to load expansion %s, as it does not have a class which" - + " extends PlaceholderExpansion", file.getName()); - return null; + Msg.severe("Failed to load expansion class %s%s", ex, clazz.getSimpleName(), reason); } - Set expansionMethods = Arrays.stream(expansionClass.getDeclaredMethods()) - .map(method -> new MethodSignature(method.getName(), method.getParameterTypes())) - .collect(Collectors.toSet()); - if (!expansionMethods.containsAll(ABSTRACT_EXPANSION_METHODS)) { - Msg.severe("Failed to load expansion %s, as it does not have the required" - + " methods declared for a PlaceholderExpansion.", file.getName()); - return null; + return Optional.empty(); + } + + /** + * Attempt to register a {@link PlaceholderExpansion} + * + * @param expansion the expansion to register + * @return if the expansion was registered + */ + @ApiStatus.Internal + public boolean register(@NotNull final PlaceholderExpansion expansion) { + final String identifier = expansion.getIdentifier().toLowerCase(Locale.ROOT); + + if (!expansion.canRegister()) { + return false; } - return expansionClass; - } catch (VerifyError | NoClassDefFoundError e) { - Msg.severe("Failed to load expansion %s (is a dependency missing?)", e, file.getName()); - return null; - } catch (Exception e) { - plugin.getLogger().log(Level.SEVERE, "Failed to load expansion file: " + file.getAbsolutePath(), e); - return null; - } - }); - } + // Avoid loading two external expansions with the same identifier + if (expansion.getExpansionType() == PlaceholderExpansion.Type.EXTERNAL && expansions.containsKey(identifier)) { + Msg.warn("Failed to load external expansion %s. Identifier is already in use.", expansion.getIdentifier()); + return false; + } + if (expansion instanceof Configurable) { + Map defaults = ((Configurable) expansion).getDefaults(); + String pre = "expansions." + identifier + "."; + FileConfiguration cfg = plugin.getConfig(); + boolean save = false; - @Nullable - public PlaceholderExpansion createExpansionInstance( - @NotNull final Class clazz) throws LinkageError { - try { - return clazz.getDeclaredConstructor().newInstance(); - } catch (final Exception ex) { - if (ex.getCause() instanceof LinkageError) { - throw ((LinkageError) ex.getCause()); - } - - Msg.warn("There was an issue with loading an expansion."); - return null; - } - } + if (defaults != null) { + for (Map.Entry entries : defaults.entrySet()) { + if (entries.getKey() == null || entries.getKey().isEmpty()) { + continue; + } + if (entries.getValue() == null) { + if (cfg.contains(pre + entries.getKey())) { + save = true; + cfg.set(pre + entries.getKey(), null); + } + } else { + if (!cfg.contains(pre + entries.getKey())) { + save = true; + cfg.set(pre + entries.getKey(), entries.getValue()); + } + } + } + } - @EventHandler - public void onQuit(@NotNull final PlayerQuitEvent event) { - for (final PlaceholderExpansion expansion : getExpansions()) { - if (!(expansion instanceof Cleanable)) { - continue; - } + if (save) { + plugin.saveConfig(); + plugin.reloadConfig(); + } + } - ((Cleanable) expansion).cleanup(event.getPlayer()); - } - } + if (expansion instanceof VersionSpecific) { + VersionSpecific nms = (VersionSpecific) expansion; + if (!nms.isCompatibleWith(PlaceholderAPIPlugin.getServerVersion())) { + Msg.warn("Your server version is incompatible with expansion %s %s", + expansion.getIdentifier(), expansion.getVersion()); + return false; + } + } - @EventHandler(priority = EventPriority.HIGH) - public void onPluginDisable(@NotNull final PluginDisableEvent event) { - final String name = event.getPlugin().getName(); - if (name.equals(plugin.getName())) { - return; + final PlaceholderExpansion removed = getExpansion(identifier); + if (removed != null && !removed.unregister()) { + return false; + } + + final ExpansionRegisterEvent event = new ExpansionRegisterEvent(expansion); + Bukkit.getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return false; + } + + expansionsLock.lock(); + try { + expansions.put(identifier, expansion); + } finally { + expansionsLock.unlock(); + } + + if (expansion instanceof Listener) { + Bukkit.getPluginManager().registerEvents(((Listener) expansion), plugin); + } + + Msg.info( + "Successfully registered %s expansion: %s [%s]", + expansion.getExpansionType().name().toLowerCase(), + expansion.getIdentifier(), + expansion.getVersion() + ); + + if (expansion instanceof Taskable) { + ((Taskable) expansion).start(); + } + + // Check eCloud for updates only if the expansion is external + if (plugin.getPlaceholderAPIConfig().isCloudEnabled() && expansion.getExpansionType() == PlaceholderExpansion.Type.EXTERNAL) { + final Optional cloudExpansionOptional = plugin.getCloudExpansionManager().findCloudExpansionByName(identifier); + if (cloudExpansionOptional.isPresent()) { + CloudExpansion cloudExpansion = cloudExpansionOptional.get(); + cloudExpansion.setHasExpansion(true); + cloudExpansion.setShouldUpdate(!cloudExpansion.getLatestVersion().equals(expansion.getVersion())); + } + } + + return true; } - for (final PlaceholderExpansion expansion : getExpansions()) { - if (!name.equalsIgnoreCase(expansion.getRequiredPlugin())) { - continue; - } + @ApiStatus.Internal + public boolean unregister(@NotNull final PlaceholderExpansion expansion) { + if (expansions.remove(expansion.getIdentifier().toLowerCase(Locale.ROOT)) == null) { + return false; + } - expansion.unregister(); - Msg.info("Unregistered placeholder expansion %s", expansion.getIdentifier()); - Msg.info("Reason: required plugin %s was disabled.", name); + Bukkit.getPluginManager().callEvent(new ExpansionUnregisterEvent(expansion)); + + if (expansion instanceof Listener) { + HandlerList.unregisterAll((Listener) expansion); + } + + if (expansion instanceof Taskable) { + ((Taskable) expansion).stop(); + } + + if (expansion instanceof Cacheable) { + ((Cacheable) expansion).clear(); + } + + if (plugin.getPlaceholderAPIConfig().isCloudEnabled()) { + plugin.getCloudExpansionManager().findCloudExpansionByName(expansion.getName()) + .ifPresent(cloud -> { + cloud.setHasExpansion(false); + cloud.setShouldUpdate(false); + }); + } + + return true; + } + + private void registerAll(@NotNull final CommandSender sender) { + Msg.info("Placeholder expansion registration initializing..."); + + Futures.onMainThread(plugin, findExpansionsOnDisk(), (classes, exception) -> { + if (exception != null) { + Msg.severe("Failed to load class files of expansion.", exception); + return; + } + + final List registered = classes.stream() + .filter(Objects::nonNull) + .map(this::register) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toList()); + + final long needsUpdate = registered.stream() + .map(expansion -> plugin.getCloudExpansionManager().findCloudExpansionByName(expansion.getName()).orElse(null)) + .filter(Objects::nonNull) + .filter(CloudExpansion::shouldUpdate) + .count(); + + StringBuilder message = new StringBuilder(registered.size() == 0 ? "&6" : "&a") + .append(registered.size()) + .append(' ') + .append("placeholder hook(s) registered!"); + + if (needsUpdate > 0) { + message.append(' ') + .append("&6") + .append(needsUpdate) + .append(' ') + .append("placeholder hook(s) have an update available."); + } + + + Msg.msg(sender, message.toString()); + + Bukkit.getPluginManager().callEvent(new ExpansionsLoadedEvent(registered)); + }); + } + + private void unregisterAll() { + for (final PlaceholderExpansion expansion : Sets.newHashSet(expansions.values())) { + if (expansion.persist()) { + continue; + } + + expansion.unregister(); + } + } + + @NotNull + public CompletableFuture<@NotNull List<@Nullable Class>> findExpansionsOnDisk() { + File[] files = folder.listFiles((dir, name) -> name.endsWith(".jar")); + if (files == null) { + return CompletableFuture.completedFuture(Collections.emptyList()); + } + + return Arrays.stream(files) + .map(this::findExpansionInFile) + .collect(Futures.collector()); + } + + @NotNull + public CompletableFuture<@Nullable Class> findExpansionInFile( + @NotNull final File file) { + return CompletableFuture.supplyAsync(() -> { + try { + final Class expansionClass = FileUtil.findClass(file, PlaceholderExpansion.class); + + if (expansionClass == null) { + Msg.severe("Failed to load expansion %s, as it does not have a class which" + + " extends PlaceholderExpansion", file.getName()); + return null; + } + + Set expansionMethods = Arrays.stream(expansionClass.getDeclaredMethods()) + .map(method -> new MethodSignature(method.getName(), method.getParameterTypes())) + .collect(Collectors.toSet()); + if (!expansionMethods.containsAll(ABSTRACT_EXPANSION_METHODS)) { + Msg.severe("Failed to load expansion %s, as it does not have the required" + + " methods declared for a PlaceholderExpansion.", file.getName()); + return null; + } + + return expansionClass; + } catch (VerifyError | NoClassDefFoundError e) { + Msg.severe("Failed to load expansion %s (is a dependency missing?)", e, file.getName()); + return null; + } catch (Exception e) { + plugin.getLogger().log(Level.SEVERE, "Failed to load expansion file: " + file.getAbsolutePath(), e); + return null; + } + }); + } + + + @Nullable + public PlaceholderExpansion createExpansionInstance( + @NotNull final Class clazz) throws LinkageError { + try { + return clazz.getDeclaredConstructor().newInstance(); + } catch (final Exception ex) { + if (ex.getCause() instanceof LinkageError) { + throw ((LinkageError) ex.getCause()); + } + + Msg.warn("There was an issue with loading an expansion."); + return null; + } + } + + + @EventHandler + public void onQuit(@NotNull final PlayerQuitEvent event) { + for (final PlaceholderExpansion expansion : getExpansions()) { + if (!(expansion instanceof Cleanable)) { + continue; + } + + ((Cleanable) expansion).cleanup(event.getPlayer()); + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPluginDisable(@NotNull final PluginDisableEvent event) { + final String name = event.getPlugin().getName(); + if (name.equals(plugin.getName())) { + return; + } + + for (final PlaceholderExpansion expansion : getExpansions()) { + if (!name.equalsIgnoreCase(expansion.getRequiredPlugin())) { + continue; + } + + expansion.unregister(); + Msg.info("Unregistered placeholder expansion %s", expansion.getIdentifier()); + Msg.info("Reason: required plugin %s was disabled.", name); + } } - } } diff --git a/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java b/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java index fe08457..c37b5a8 100644 --- a/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java +++ b/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java @@ -22,6 +22,7 @@ package me.clip.placeholderapi.replacer; import java.util.Locale; import java.util.function.Function; + import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; @@ -30,108 +31,110 @@ import org.jetbrains.annotations.Nullable; public final class CharsReplacer implements Replacer { - @NotNull - private final Closure closure; + @NotNull + private final Closure closure; - public CharsReplacer(@NotNull final Closure closure) { - this.closure = closure; - } - - - @NotNull - @Override - public String apply(@NotNull final String text, @Nullable final OfflinePlayer player, - @NotNull final Function lookup) { - final char[] chars = text.toCharArray(); - final StringBuilder builder = new StringBuilder(text.length()); - - final StringBuilder identifier = new StringBuilder(); - final StringBuilder parameters = new StringBuilder(); - - for (int i = 0; i < chars.length; i++) { - final char l = chars[i]; - - if (l != closure.head || i + 1 >= chars.length) { - builder.append(l); - continue; - } - - boolean identified = false; - boolean invalid = true; - boolean hadSpace = false; - - while (++i < chars.length) { - final char p = chars[i]; - - if (p == ' ' && !identified) { - hadSpace = true; - break; - } - if (p == closure.tail) { - invalid = false; - break; - } - - if (p == '_' && !identified) { - identified = true; - continue; - } - - if (identified) { - parameters.append(p); - } else { - identifier.append(p); - } - } - - final String identifierString = identifier.toString(); - final String lowercaseIdentifierString = identifierString.toLowerCase(Locale.ROOT); - final String parametersString = parameters.toString(); - - identifier.setLength(0); - parameters.setLength(0); - - if (invalid) { - builder.append(closure.head).append(identifierString); - - if (identified) { - builder.append('_').append(parametersString); - } - - if (hadSpace) { - builder.append(' '); - } - continue; - } - - final PlaceholderExpansion placeholder = lookup.apply(lowercaseIdentifierString); - if (placeholder == null) { - builder.append(closure.head).append(identifierString); - - if (identified) { - builder.append('_'); - } - - builder.append(parametersString).append(closure.tail); - continue; - } - - final String replacement = placeholder.onRequest(player, parametersString); - if (replacement == null) { - builder.append(closure.head).append(identifierString); - - if (identified) { - builder.append('_'); - } - - builder.append(parametersString).append(closure.tail); - continue; - } - - builder.append(replacement); + public CharsReplacer(@NotNull final Closure closure) { + this.closure = closure; } - return builder.toString(); - } + + @NotNull + @Override + public String apply(@NotNull final String text, @Nullable final OfflinePlayer player, + @NotNull final Function lookup) { + final char[] chars = text.toCharArray(); + // Woo! Hlello %player_name% + // Woo! GHsda PiggyPiglet + final StringBuilder builder = new StringBuilder(text.length()); + + final StringBuilder identifier = new StringBuilder(); + final StringBuilder parameters = new StringBuilder(); + + for (int i = 0; i < chars.length; i++) { + final char l = chars[i]; + + if (l != closure.head || i + 1 >= chars.length) { + builder.append(l); + continue; + } + + boolean identified = false; + boolean invalid = true; + boolean hadSpace = false; + + while (++i < chars.length) { + final char p = chars[i]; + + if (p == ' ' && !identified) { + hadSpace = true; + break; + } + if (p == closure.tail) { + invalid = false; + break; + } + + if (p == '_' && !identified) { + identified = true; + continue; + } + + if (identified) { + parameters.append(p); + } else { + identifier.append(p); + } + } + + final String identifierString = identifier.toString(); + final String lowercaseIdentifierString = identifierString.toLowerCase(Locale.ROOT); + final String parametersString = parameters.toString(); + + identifier.setLength(0); + parameters.setLength(0); + + if (invalid) { + builder.append(closure.head).append(identifierString); + + if (identified) { + builder.append('_').append(parametersString); + } + + if (hadSpace) { + builder.append(' '); + } + continue; + } + + final PlaceholderExpansion placeholder = lookup.apply(lowercaseIdentifierString); + if (placeholder == null) { + builder.append(closure.head).append(identifierString); + + if (identified) { + builder.append('_'); + } + + builder.append(parametersString).append(closure.tail); + continue; + } + + final String replacement = placeholder.onRequest(player, parametersString); + if (replacement == null) { + builder.append(closure.head).append(identifierString); + + if (identified) { + builder.append('_'); + } + + builder.append(parametersString).append(closure.tail); + continue; + } + + builder.append(replacement); + } + + return builder.toString(); + } } diff --git a/src/main/java/me/clip/placeholderapi/replacer/ComponentCharsReplacer.java b/src/main/java/me/clip/placeholderapi/replacer/ComponentCharsReplacer.java deleted file mode 100644 index 233ef09..0000000 --- a/src/main/java/me/clip/placeholderapi/replacer/ComponentCharsReplacer.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * This file is part of adventure, licensed under the MIT License. - * - * Copyright (c) 2017-2025 KyoriPowered - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package me.clip.placeholderapi.replacer; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.regex.MatchResult; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.google.common.collect.Lists; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import net.kyori.adventure.text.*; -import net.kyori.adventure.text.event.HoverEvent; -import net.kyori.adventure.text.format.Style; -import net.kyori.adventure.text.renderer.ComponentRenderer; -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * A renderer performing a replacement on every {@link TextComponent} element of a component tree. - */ -final class ComponentCharsReplacer implements ComponentRenderer { - //static final TextReplacementRenderer INSTANCE = new TextReplacementRenderer(); - private final OfflinePlayer player; - private final Function lookup; - private static final Closure CLOSURE = Closure.PERCENT; - - enum Closure { - BRACKET('{', '}'), - PERCENT('%', '%'); - - - public final char head, tail; - - Closure(final char head, final char tail) { - this.head = head; - this.tail = tail; - } - } - - public ComponentCharsReplacer(@Nullable final OfflinePlayer player, - @NotNull final Function lookup) { - this.player = player; - this.lookup = lookup; - } - - @Override - public Component render(final Component component, final State state) { - if (!state.running) return component; - final boolean prevFirstMatch = state.firstMatch; - state.firstMatch = true; - - final List oldChildren = component.children(); - final int oldChildrenSize = oldChildren.size(); - Style oldStyle = component.style(); - List children = null; - Component modified = component; - // replace the component itself - if (component instanceof TextComponent) { - TextComponent tc = (TextComponent) component; - final String content = tc.content(); - - final char[] chars = content.toCharArray(); - final StringBuilder identifier = new StringBuilder(); - final StringBuilder parameters = new StringBuilder(); - - final Map, Component> replacements = new HashMap<>(); - - for (int i = 0; i < chars.length; i++) { - final char l = chars[i]; - - if (l != CLOSURE.head || i + 1 >= chars.length) { - continue; - } - - boolean identified = false; - boolean invalid = true; - boolean hadSpace = false; - - while (++i < chars.length) { - final char p = chars[i]; - - if (p == ' ' && !identified) { - hadSpace = true; - break; - } - - if (p == CLOSURE.tail) { - invalid = false; - break; - } - - if (p == '_' && !identified) { - identified = true; - break; - } - - if (identified) { - parameters.append(p); - } else { - identifier.append(p); - } - } - - final String identifierString = identifier.toString(); - final String lowerIdentifiedString = identifierString.toLowerCase(); - final String parametersString = parameters.toString(); - - identifier.setLength(0); - parameters.setLength(0); - - if (invalid) { - continue; - } - - replacements.put(Lists.newArrayList(i, i + identifierString.length() + parametersString.length()), lookup.apply(lowerIdentifiedString).onPlaceholderComponentRequest(player, parametersString)); - - - } - - - // do something with our replacements - - - - - final Matcher matcher = state.pattern.matcher(content); - int replacedUntil = 0; // last index handled - while (matcher.find()) { - final PatternReplacementResult result = state.continuer.shouldReplace(matcher, ++state.matchCount, state.replaceCount); - - if (matcher.start() == 0) { - // if we're a full match, modify the component directly - if (matcher.end() == content.length()) { - final ComponentLike replacement = state.replacement.apply(matcher, Component.text().content(matcher.group()) - .style(component.style())); - - modified = replacement == null ? Component.empty() : replacement.asComponent(); - - if (modified.style().hoverEvent() != null) { - oldStyle = oldStyle.hoverEvent(null); // Remove original hover if it has been replaced completely - } - - // merge style of the match into this component to prevent unexpected loss of style - modified = modified.style(modified.style().merge(component.style(), Style.Merge.Strategy.IF_ABSENT_ON_TARGET)); - - if (children == null) { // Prepare children - children = new ArrayList<>(oldChildrenSize + modified.children().size()); - children.addAll(modified.children()); - } - } else { - // otherwise, work on a child of the root node - modified = Component.text("", component.style()); - final ComponentLike child = state.replacement.apply(matcher, Component.text().content(matcher.group())); - if (child != null) { - if (children == null) { - children = new ArrayList<>(oldChildrenSize + 1); - } - children.add(child.asComponent()); - } - } - } else { - if (children == null) { - children = new ArrayList<>(oldChildrenSize + 2); - } - if (state.firstMatch) { - // truncate parent to content before match - modified = ((TextComponent) component).content(content.substring(0, matcher.start())); - } else if (replacedUntil < matcher.start()) { - children.add(Component.text(content.substring(replacedUntil, matcher.start()))); - } - final ComponentLike builder = state.replacement.apply(matcher, Component.text().content(matcher.group())); - if (builder != null) { - children.add(builder.asComponent()); - } - } - state.replaceCount++; - state.firstMatch = false; - replacedUntil = matcher.end(); - } - if (replacedUntil < content.length()) { - // append trailing content - if (replacedUntil > 0) { - if (children == null) { - children = new ArrayList<>(oldChildrenSize); - } - children.add(Component.text(content.substring(replacedUntil))); - } - // otherwise, we haven't modified the component, so nothing to change - } - } else if (modified instanceof TranslatableComponent) { // get TranslatableComponent with() args - final List args = ((TranslatableComponent) modified).arguments(); - List newArgs = null; - for (int i = 0, size = args.size(); i < size; i++) { - final TranslationArgument original = args.get(i); - final TranslationArgument replaced = original.value() instanceof Component ? TranslationArgument.component(this.render((Component) original.value(), state)) : original; - if (replaced != original) { - if (newArgs == null) { - newArgs = new ArrayList<>(size); - if (i > 0) { - newArgs.addAll(args.subList(0, i)); - } - } - } - if (newArgs != null) { - newArgs.add(replaced); - } - } - if (newArgs != null) { - modified = ((TranslatableComponent) modified).arguments(newArgs); - } - } - // Only visit children if we're running - if (state.running) { - // hover event - if (state.replaceInsideHoverEvents) { - final HoverEvent event = oldStyle.hoverEvent(); - if (event != null) { - final HoverEvent rendered = event.withRenderedValue(this, state); - if (event != rendered) { - modified = modified.style(s -> s.hoverEvent(rendered)); - } - } - } - // Children - boolean first = true; - for (int i = 0; i < oldChildrenSize; i++) { - final Component child = oldChildren.get(i); - final Component replaced = this.render(child, state); - if (replaced != child) { - if (children == null) { - children = new ArrayList<>(oldChildrenSize); - } - if (first) { - children.addAll(oldChildren.subList(0, i)); - } - first = false; - } - if (children != null) { - children.add(replaced); - first = false; - } - } - } else { - // we're not visiting children, re-add original children if necessary - if (children != null) { - children.addAll(oldChildren); - } - } - - state.firstMatch = prevFirstMatch; - // Update the modified component with new children - if (children != null) { - return modified.children(children); - } - return modified; - } - - static final class State { - final Pattern pattern; - final BiFunction replacement; - final TextReplacementConfig.Condition continuer; - final boolean replaceInsideHoverEvents; - boolean running = true; - int matchCount = 0; - int replaceCount = 0; - boolean firstMatch = true; - - State(final Pattern pattern, final BiFunction replacement, final TextReplacementConfig.Condition continuer, final boolean replaceInsideHoverEvents) { - this.pattern = pattern; - this.replacement = replacement; - this.continuer = continuer; - this.replaceInsideHoverEvents = replaceInsideHoverEvents; - } - } -} \ No newline at end of file diff --git a/src/main/java/me/clip/placeholderapi/replacer/ComponentReplacer.java b/src/main/java/me/clip/placeholderapi/replacer/ComponentReplacer.java new file mode 100644 index 0000000..ae02b40 --- /dev/null +++ b/src/main/java/me/clip/placeholderapi/replacer/ComponentReplacer.java @@ -0,0 +1,146 @@ +package me.clip.placeholderapi.replacer; + +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import net.kyori.adventure.text.*; +import net.kyori.adventure.text.format.Style; +import org.bukkit.OfflinePlayer; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.function.Function; + +public final class ComponentReplacer { + public Component replace(Component component, OfflinePlayer player, Function function) { + Component modified = component; + + final List oldChildren = component.children(); + final int oldChildrenSize = oldChildren.size(); + List children = null; + + if (component instanceof TextComponent) { + TextComponent tc = (TextComponent) component; + final String content = tc.content(); + + final char[] chars = content.toCharArray(); + + final StringBuilder identifier = new StringBuilder(); + final StringBuilder parameters = new StringBuilder(); + + for (int i = 0; i < chars.length; i++) { + final char l = chars[i]; + + if (l != '%' || i + 1 >= chars.length) { + continue; + } + + final int start = i; + + boolean identified = false; + boolean invalid = true; + + while (++i < chars.length) { + final char p = chars[i]; + + if (p == ' ' && !identified) { + break; + } + + if (p == '%') { + invalid = false; + break; + } + + if (p == '_' && !identified) { + identified = true; + continue; + } + + if (identified) { + parameters.append(p); + } else { + identifier.append(p); + } + } + + final String identifierString = identifier.toString(); + final String lowercaseIdentifierString = identifierString.toLowerCase(Locale.ROOT); + final String parametersString = parameters.toString(); + + identifier.setLength(0); + parameters.setLength(0); + + if (invalid) { + continue; + } + + final PlaceholderExpansion expansion = function.apply(lowercaseIdentifierString); + + if (expansion == null) { + continue; + } + + final String placeholderValue = expansion.onRequest(player, parametersString); + + if (placeholderValue == null) { + continue; + } + + if (start == 0) { + // if we're a full match, modify the component directly + if (i == content.length() - 1) { + final ComponentLike replacement = Component.text(placeholderValue).style(component.style()); + + modified = replacement.asComponent(); + Style modStyle = modified.style(); + + if (modStyle.hoverEvent() != null) { + Object hoverValue = modStyle.hoverEvent().value(); + + if (hoverValue instanceof Component) { + final Component replacedHoverComponent = replace((Component) hoverValue, player, function); + + if (replacedHoverComponent != hoverValue) { + modified.style(); + } + } + } + + if (modStyle.clickEvent() != null) { + String clickValue = + } + } + } + } + + } else if (component instanceof TranslatableComponent) { + TranslatableComponent tc = (TranslatableComponent) component; + final List args = tc.arguments(); + List newArgs = null; + for (int i = 0, size = args.size(); i < size; i++) { + final TranslationArgument original = args.get(i); + TranslationArgument replacement = original instanceof Component ? TranslationArgument.component(replace((Component) original, player, function)) : original; + + if (original != replacement) { + if (newArgs == null) { + newArgs = new ArrayList<>(size); + + if (i > 0) { + newArgs.addAll(args.subList(0, i)); + } + } + } + + if (newArgs != null) { + newArgs.add(replacement); + } + } + + if (newArgs != null) { + modified = ((TranslatableComponent) modified).arguments(newArgs); + } + } + + return modified; + } +} diff --git a/src/main/java/me/clip/placeholderapi/replacer/ExactReplacer.java b/src/main/java/me/clip/placeholderapi/replacer/ExactReplacer.java new file mode 100644 index 0000000..a4c4b20 --- /dev/null +++ b/src/main/java/me/clip/placeholderapi/replacer/ExactReplacer.java @@ -0,0 +1,48 @@ +package me.clip.placeholderapi.replacer; + +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import org.bukkit.OfflinePlayer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Function; +import java.util.regex.Pattern; + +public class ExactReplacer implements Replacer { + private static final Pattern DELIMITER = Pattern.compile("_"); + + @NotNull + @Override + public String apply(@NotNull String text, @Nullable final OfflinePlayer player, + @NotNull final Function lookup) { + text = text.substring(1, text.length() - 1); + final String[] parts = DELIMITER.split(text); + final PlaceholderExpansion expansion; + + if (parts.length == 0) { + expansion = lookup.apply(text); + } else { + expansion = lookup.apply(parts[0]); + } + + if (expansion == null) { + return text; + } + + final String params; + + if (text.endsWith("_")) { + params = ""; + } else { + params = text.substring(text.indexOf('_') + 1); + } + + final String result = expansion.onRequest(player, params); + + if (result == null) { + return text; + } + + return result; + } +} diff --git a/src/main/java/me/clip/placeholderapi/replacer/Replacer.java b/src/main/java/me/clip/placeholderapi/replacer/Replacer.java index e0c6e48..3cbc13e 100644 --- a/src/main/java/me/clip/placeholderapi/replacer/Replacer.java +++ b/src/main/java/me/clip/placeholderapi/replacer/Replacer.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.replacer; import java.util.function.Function; + import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; @@ -28,22 +29,22 @@ import org.jetbrains.annotations.Nullable; public interface Replacer { - @NotNull - String apply(@NotNull final String text, @Nullable final OfflinePlayer player, - @NotNull final Function lookup); + @NotNull + String apply(@NotNull final String text, @Nullable final OfflinePlayer player, + @NotNull final Function lookup); - enum Closure { - BRACKET('{', '}'), - PERCENT('%', '%'); + enum Closure { + BRACKET('{', '}'), + PERCENT('%', '%'); - public final char head, tail; + public final char head, tail; - Closure(final char head, final char tail) { - this.head = head; - this.tail = tail; + Closure(final char head, final char tail) { + this.head = head; + this.tail = tail; + } } - } } diff --git a/src/main/java/me/clip/placeholderapi/util/FileUtil.java b/src/main/java/me/clip/placeholderapi/util/FileUtil.java index 5d41c8f..3a78150 100644 --- a/src/main/java/me/clip/placeholderapi/util/FileUtil.java +++ b/src/main/java/me/clip/placeholderapi/util/FileUtil.java @@ -34,44 +34,44 @@ import java.util.jar.JarInputStream; public class FileUtil { - @Nullable - public static Class findClass(@NotNull final File file, - @NotNull final Class clazz) throws IOException, ClassNotFoundException { - if (!file.exists()) { - return null; - } - - final URL jar = file.toURI().toURL(); - final URLClassLoader loader = new URLClassLoader(new URL[]{jar}, clazz.getClassLoader()); - final List matches = new ArrayList<>(); - final List> classes = new ArrayList<>(); - - try (final JarInputStream stream = new JarInputStream(jar.openStream())) { - JarEntry entry; - while ((entry = stream.getNextJarEntry()) != null) { - final String name = entry.getName(); - if (name.isEmpty() || !name.endsWith(".class")) { - continue; + @Nullable + public static Class findClass(@NotNull final File file, + @NotNull final Class clazz) throws IOException, ClassNotFoundException { + if (!file.exists()) { + return null; } - matches.add(name.substring(0, name.lastIndexOf('.')).replace('/', '.')); - } + final URL jar = file.toURI().toURL(); + final URLClassLoader loader = new URLClassLoader(new URL[]{jar}, clazz.getClassLoader()); + final List matches = new ArrayList<>(); + final List> classes = new ArrayList<>(); - for (final String match : matches) { - try { - final Class loaded = loader.loadClass(match); - if (clazz.isAssignableFrom(loaded)) { - classes.add(loaded.asSubclass(clazz)); - } - } catch (final NoClassDefFoundError ignored) { + try (final JarInputStream stream = new JarInputStream(jar.openStream())) { + JarEntry entry; + while ((entry = stream.getNextJarEntry()) != null) { + final String name = entry.getName(); + if (name.isEmpty() || !name.endsWith(".class")) { + continue; + } + + matches.add(name.substring(0, name.lastIndexOf('.')).replace('/', '.')); + } + + for (final String match : matches) { + try { + final Class loaded = loader.loadClass(match); + if (clazz.isAssignableFrom(loaded)) { + classes.add(loaded.asSubclass(clazz)); + } + } catch (final NoClassDefFoundError ignored) { + } + } } - } + if (classes.isEmpty()) { + loader.close(); + return null; + } + return classes.get(0); } - if (classes.isEmpty()) { - loader.close(); - return null; - } - return classes.get(0); - } } diff --git a/src/main/java/me/clip/placeholderapi/util/Format.java b/src/main/java/me/clip/placeholderapi/util/Format.java index a149ec5..bc969c6 100644 --- a/src/main/java/me/clip/placeholderapi/util/Format.java +++ b/src/main/java/me/clip/placeholderapi/util/Format.java @@ -29,6 +29,7 @@ import static java.util.stream.IntStream.range; import java.util.List; import java.util.Optional; + import org.jetbrains.annotations.NotNull; /** @@ -36,35 +37,35 @@ import org.jetbrains.annotations.NotNull; */ public final class Format { - private Format() {} + private Format() {} - @NotNull - public static Optional> tablify(@NotNull final Align align, - @NotNull final List> rows) { - return findSpacing(rows) - .map(spacing -> buildFormat(align, spacing)) - .map(format -> rows.stream() - .map( - row -> String.format(format, row.toArray()).substring(align == Align.RIGHT ? 2 : 0)) - .collect(toList())); - } + @NotNull + public static Optional> tablify(@NotNull final Align align, + @NotNull final List> rows) { + return findSpacing(rows) + .map(spacing -> buildFormat(align, spacing)) + .map(format -> rows.stream() + .map( + row -> String.format(format, row.toArray()).substring(align == Align.RIGHT ? 2 : 0)) + .collect(toList())); + } - @NotNull - private static String buildFormat(@NotNull final Align align, final int[] spacing) { - return stream(spacing) - .mapToObj(space -> "%" + (align == Align.LEFT ? "-" : "") + (space + 2) + "s") - .collect(joining()); - } + @NotNull + private static String buildFormat(@NotNull final Align align, final int[] spacing) { + return stream(spacing) + .mapToObj(space -> "%" + (align == Align.LEFT ? "-" : "") + (space + 2) + "s") + .collect(joining()); + } - @NotNull - private static Optional findSpacing(@NotNull final List> rows) { - return rows.stream() - .map(row -> row.stream().mapToInt(String::length).toArray()) - .reduce((l, r) -> range(0, min(l.length, r.length)).map(i -> max(l[i], r[i])).toArray()); - } + @NotNull + private static Optional findSpacing(@NotNull final List> rows) { + return rows.stream() + .map(row -> row.stream().mapToInt(String::length).toArray()) + .reduce((l, r) -> range(0, min(l.length, r.length)).map(i -> max(l[i], r[i])).toArray()); + } - public enum Align { - LEFT, RIGHT - } + public enum Align { + LEFT, RIGHT + } } diff --git a/src/main/java/me/clip/placeholderapi/util/Futures.java b/src/main/java/me/clip/placeholderapi/util/Futures.java index 29d7fa7..ad76040 100644 --- a/src/main/java/me/clip/placeholderapi/util/Futures.java +++ b/src/main/java/me/clip/placeholderapi/util/Futures.java @@ -35,45 +35,45 @@ import org.jetbrains.annotations.NotNull; public final class Futures { - private Futures() {} + private Futures() {} - public static void onMainThread(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CompletableFuture future, - @NotNull final BiConsumer consumer) { - future.whenComplete((value, exception) -> { - if (Bukkit.isPrimaryThread()) { - consumer.accept(value, exception); - } else { - plugin.getScheduler().runTask(() -> consumer.accept(value, exception)); - } - }); - } + public static void onMainThread(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CompletableFuture future, + @NotNull final BiConsumer consumer) { + future.whenComplete((value, exception) -> { + if (Bukkit.isPrimaryThread()) { + consumer.accept(value, exception); + } else { + plugin.getScheduler().runTask(() -> consumer.accept(value, exception)); + } + }); + } - @NotNull - public static Collector, ?, CompletableFuture>> collector() { - return Collectors.collectingAndThen(Collectors.toList(), Futures::of); - } + @NotNull + public static Collector, ?, CompletableFuture>> collector() { + return Collectors.collectingAndThen(Collectors.toList(), Futures::of); + } - @NotNull - public static CompletableFuture> of( - @NotNull final Stream> futures) { - return of(futures.collect(Collectors.toList())); - } + @NotNull + public static CompletableFuture> of( + @NotNull final Stream> futures) { + return of(futures.collect(Collectors.toList())); + } - @NotNull - public static CompletableFuture> of( - @NotNull final Collection> futures) { - return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) - .thenApplyAsync($ -> awaitCompletion(futures)); - } + @NotNull + public static CompletableFuture> of( + @NotNull final Collection> futures) { + return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) + .thenApplyAsync($ -> awaitCompletion(futures)); + } - @NotNull - private static List awaitCompletion( - @NotNull final Collection> futures) { - return futures.stream().map(CompletableFuture::join).collect(Collectors.toList()); - } + @NotNull + private static List awaitCompletion( + @NotNull final Collection> futures) { + return futures.stream().map(CompletableFuture::join).collect(Collectors.toList()); + } } diff --git a/src/main/java/me/clip/placeholderapi/util/Msg.java b/src/main/java/me/clip/placeholderapi/util/Msg.java index 84307c7..ed179ad 100644 --- a/src/main/java/me/clip/placeholderapi/util/Msg.java +++ b/src/main/java/me/clip/placeholderapi/util/Msg.java @@ -23,6 +23,7 @@ package me.clip.placeholderapi.util; import java.util.Arrays; import java.util.logging.Level; import java.util.stream.Collectors; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -30,50 +31,50 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; public final class Msg { - - public static void log(Level level, String msg, Object... args) { - PlaceholderAPIPlugin.getInstance().getLogger().log(level, String.format(msg, args)); - } - - public static void info(String msg, Object... args) { - log(Level.INFO, msg, args); - } - - public static void warn(String msg, Object... args) { - log(Level.WARNING, msg, args); - } - - public static void warn(String msg, Throwable throwable, Object... args){ - PlaceholderAPIPlugin.getInstance().getLogger().log(Level.WARNING, String.format(msg, args), throwable); - } - - public static void severe(String msg, Object... args) { - log(Level.SEVERE, msg, args); - } - - public static void severe(String msg, Throwable throwable, Object... args) { - PlaceholderAPIPlugin.getInstance().getLogger().log(Level.SEVERE, String.format(msg, args), throwable); - } - - public static void msg(@NotNull final CommandSender sender, @NotNull final String... messages) { - if (messages.length == 0) { - return; + + public static void log(Level level, String msg, Object... args) { + PlaceholderAPIPlugin.getInstance().getLogger().log(level, String.format(msg, args)); } - sender.sendMessage(Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n"))); - } - - public static void broadcast(@NotNull final String... messages) { - if (messages.length == 0) { - return; + public static void info(String msg, Object... args) { + log(Level.INFO, msg, args); } - Bukkit.broadcastMessage( - Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n"))); - } + public static void warn(String msg, Object... args) { + log(Level.WARNING, msg, args); + } - public static String color(@NotNull final String text) { - return ChatColor.translateAlternateColorCodes('&', text); - } + public static void warn(String msg, Throwable throwable, Object... args) { + PlaceholderAPIPlugin.getInstance().getLogger().log(Level.WARNING, String.format(msg, args), throwable); + } + + public static void severe(String msg, Object... args) { + log(Level.SEVERE, msg, args); + } + + public static void severe(String msg, Throwable throwable, Object... args) { + PlaceholderAPIPlugin.getInstance().getLogger().log(Level.SEVERE, String.format(msg, args), throwable); + } + + public static void msg(@NotNull final CommandSender sender, @NotNull final String... messages) { + if (messages.length == 0) { + return; + } + + sender.sendMessage(Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n"))); + } + + public static void broadcast(@NotNull final String... messages) { + if (messages.length == 0) { + return; + } + + Bukkit.broadcastMessage( + Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n"))); + } + + public static String color(@NotNull final String text) { + return ChatColor.translateAlternateColorCodes('&', text); + } } diff --git a/src/main/java/me/clip/placeholderapi/util/TimeFormat.java b/src/main/java/me/clip/placeholderapi/util/TimeFormat.java index f66f9da..4dc2a88 100644 --- a/src/main/java/me/clip/placeholderapi/util/TimeFormat.java +++ b/src/main/java/me/clip/placeholderapi/util/TimeFormat.java @@ -21,8 +21,8 @@ package me.clip.placeholderapi.util; public enum TimeFormat { - DAYS, - HOURS, - MINUTES, - SECONDS + DAYS, + HOURS, + MINUTES, + SECONDS } diff --git a/src/main/java/me/clip/placeholderapi/util/TimeUtil.java b/src/main/java/me/clip/placeholderapi/util/TimeUtil.java index d23a571..24db4d8 100644 --- a/src/main/java/me/clip/placeholderapi/util/TimeUtil.java +++ b/src/main/java/me/clip/placeholderapi/util/TimeUtil.java @@ -26,71 +26,71 @@ import java.util.StringJoiner; public class TimeUtil { - public static String getRemaining(final int seconds, final TimeFormat type) { - return getRemaining((long) seconds, type); - } - - public static String getRemaining(final long seconds, final TimeFormat type) { - switch (type) { - default: - return String.valueOf(seconds); - - case SECONDS: - return String.valueOf(seconds % 60); - - case MINUTES: - return String.valueOf((seconds / 60) % 60); - - case HOURS: - return String.valueOf((seconds / 3600) % 24); - - case DAYS: - return String.valueOf(seconds / 86400); - } - } - - /** - * Format the given value with s, m, h and d (seconds, minutes, hours and days) - * - * @param duration {@link Duration} (eg, Duration.of(20, {@link ChronoUnit#SECONDS}) for 20 - * seconds) - * @return formatted time - */ - public static String getTime(final Duration duration) { - return getTime(duration.getSeconds()); - } - - public static String getTime(final int seconds) { - return getTime((long) seconds); - } - - public static String getTime(long seconds) { - final StringJoiner joiner = new StringJoiner(" "); - - long minutes = seconds / 60; - long hours = minutes / 60; - final long days = hours / 24; - - seconds %= 60; - minutes %= 60; - hours %= 24; - - if (days > 0) { - joiner.add(days + "d"); + public static String getRemaining(final int seconds, final TimeFormat type) { + return getRemaining((long) seconds, type); } - if (hours > 0) { - joiner.add(hours + "h"); + public static String getRemaining(final long seconds, final TimeFormat type) { + switch (type) { + default: + return String.valueOf(seconds); + + case SECONDS: + return String.valueOf(seconds % 60); + + case MINUTES: + return String.valueOf((seconds / 60) % 60); + + case HOURS: + return String.valueOf((seconds / 3600) % 24); + + case DAYS: + return String.valueOf(seconds / 86400); + } } - if (minutes > 0) { - joiner.add(minutes + "m"); + /** + * Format the given value with s, m, h and d (seconds, minutes, hours and days) + * + * @param duration {@link Duration} (eg, Duration.of(20, {@link ChronoUnit#SECONDS}) for 20 + * seconds) + * @return formatted time + */ + public static String getTime(final Duration duration) { + return getTime(duration.getSeconds()); } - if (seconds > 0) { - joiner.add(seconds + "s"); + public static String getTime(final int seconds) { + return getTime((long) seconds); } - return joiner.toString(); - } + public static String getTime(long seconds) { + final StringJoiner joiner = new StringJoiner(" "); + + long minutes = seconds / 60; + long hours = minutes / 60; + final long days = hours / 24; + + seconds %= 60; + minutes %= 60; + hours %= 24; + + if (days > 0) { + joiner.add(days + "d"); + } + + if (hours > 0) { + joiner.add(hours + "h"); + } + + if (minutes > 0) { + joiner.add(minutes + "m"); + } + + if (seconds > 0) { + joiner.add(seconds + "s"); + } + + return joiner.toString(); + } } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 2546065..da33c49 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -12,6 +12,8 @@ commands: placeholderapi: description: "PlaceholderAPI Command" aliases: ["papi"] + test: + description: "yes" permissions: placeholderapi.*: