From dcc8dad4eab8312a69ad3c64e9053ec886182ecc Mon Sep 17 00:00:00 2001 From: extendedclip Date: Fri, 31 Jul 2020 22:52:07 -0400 Subject: [PATCH] Format to Daddy code style --- .github/workflows/wiki.yml | 58 +- build.gradle | 130 ++-- .../clip/placeholderapi/PlaceholderAPI.java | 7 +- .../placeholderapi/PlaceholderAPIPlugin.java | 355 ++++----- .../clip/placeholderapi/PlaceholderHook.java | 40 +- .../commands/PlaceholderCommand.java | 129 ++-- .../commands/PlaceholderCommandRouter.java | 151 ++-- .../commands/impl/cloud/CommandECloud.java | 195 +++-- .../impl/cloud/CommandECloudClear.java | 28 +- .../impl/cloud/CommandECloudDownload.java | 158 ++-- .../cloud/CommandECloudExpansionInfo.java | 177 +++-- .../cloud/CommandECloudExpansionList.java | 504 ++++++------- .../CommandECloudExpansionPlaceholders.java | 104 ++- .../impl/cloud/CommandECloudRefresh.java | 31 +- .../impl/cloud/CommandECloudStatus.java | 49 +- .../impl/cloud/CommandECloudToggle.java | 75 +- .../impl/cloud/CommandECloudUpdate.java | 173 +++-- .../commands/impl/local/CommandDump.java | 328 ++++---- .../impl/local/CommandExpansionRegister.java | 133 ++-- .../local/CommandExpansionUnregister.java | 77 +- .../commands/impl/local/CommandHelp.java | 74 +- .../commands/impl/local/CommandInfo.java | 141 ++-- .../commands/impl/local/CommandList.java | 47 +- .../commands/impl/local/CommandParse.java | 323 ++++---- .../commands/impl/local/CommandReload.java | 24 +- .../commands/impl/local/CommandVersion.java | 34 +- .../configuration/ExpansionSort.java | 32 +- .../configuration/PlaceholderAPIConfig.java | 110 ++- .../events/ExpansionRegisterEvent.java | 73 +- .../events/ExpansionUnregisterEvent.java | 50 +- .../events/PlaceholderHookUnloadEvent.java | 65 +- .../exceptions/NoDefaultCommandException.java | 7 +- .../placeholderapi/expansion/Cacheable.java | 8 +- .../placeholderapi/expansion/Cleanable.java | 12 +- .../expansion/Configurable.java | 20 +- .../placeholderapi/expansion/NMSVersion.java | 30 +- .../expansion/PlaceholderExpansion.java | 429 +++++------ .../placeholderapi/expansion/Relational.java | 2 +- .../placeholderapi/expansion/Taskable.java | 20 +- .../placeholderapi/expansion/Version.java | 30 +- .../expansion/VersionSpecific.java | 14 +- .../expansion/cloud/CloudExpansion.java | 310 ++++---- .../manager/CloudExpansionManager.java | 371 +++++---- .../manager/LocalExpansionManager.java | 706 ++++++++---------- .../clip/placeholderapi/libs/JSONMessage.java | 116 +-- .../listeners/ServerLoadEventListener.java | 47 +- .../replacer/CharsReplacer.java | 248 +++--- .../replacer/RegexReplacer.java | 70 +- .../placeholderapi/replacer/Replacer.java | 31 +- .../updatechecker/UpdateChecker.java | 155 ++-- .../me/clip/placeholderapi/util/FileUtil.java | 79 +- .../me/clip/placeholderapi/util/Format.java | 70 +- .../me/clip/placeholderapi/util/Futures.java | 78 +- .../java/me/clip/placeholderapi/util/Msg.java | 44 +- .../clip/placeholderapi/util/TimeFormat.java | 8 +- .../me/clip/placeholderapi/util/TimeUtil.java | 269 +++---- src/main/resources/plugin.yml | 18 +- .../java/me/clip/placeholderapi/Values.java | 102 ++- .../replacer/ReplacerBenchmarks.java | 39 +- .../replacer/ReplacerUnitTester.java | 108 +-- 60 files changed, 3481 insertions(+), 3835 deletions(-) diff --git a/.github/workflows/wiki.yml b/.github/workflows/wiki.yml index 97be2c0..02864b8 100644 --- a/.github/workflows/wiki.yml +++ b/.github/workflows/wiki.yml @@ -10,43 +10,43 @@ on: # Only trigger when the push changes any files in the wiki-folder. # paths: - - 'wiki/**' + - 'wiki/**' branches: - - 'docs/wiki' + - 'docs/wiki' # # Releases cause this action to also fire. # Using this prevents this problem. # tags-ignore: - - '**' + - '**' jobs: update: runs-on: ubuntu-latest steps: - - name: 'Checkout Code' - uses: actions/Checkout@v2 - - name: 'Update Wiki' - uses: docker://decathlon/wiki-page-creator-action:latest - env: - # - # We can use the E-Mail and Name of the GitHub Actions account - # for our convenience. - # - ACTION_MAIL: 'actions@github.com' - ACTION_NAME: 'github-actions[bot]' - # - # We (sadly) have to use a PAT (Personal Access Token) for this action. - # - GH_PAT: '${{ secrets.WORKFLOWPAT }}' - OWNER: 'PlaceholderAPI' - REPO_NAME: 'PlaceholderAPI' - # - # We only want to target files in the wiki folder - # - MD_FOLDER: 'wiki' - WIKI_PUSH_MESSAGE: '${{ github.event.commits[0].message }}' - # - # We skip/ignore the README.md file in the Wiki folder - # - SKIP_MD: README.md + - name: 'Checkout Code' + uses: actions/Checkout@v2 + - name: 'Update Wiki' + uses: docker://decathlon/wiki-page-creator-action:latest + env: + # + # We can use the E-Mail and Name of the GitHub Actions account + # for our convenience. + # + ACTION_MAIL: 'actions@github.com' + ACTION_NAME: 'github-actions[bot]' + # + # We (sadly) have to use a PAT (Personal Access Token) for this action. + # + GH_PAT: '${{ secrets.WORKFLOWPAT }}' + OWNER: 'PlaceholderAPI' + REPO_NAME: 'PlaceholderAPI' + # + # We only want to target files in the wiki folder + # + MD_FOLDER: 'wiki' + WIKI_PUSH_MESSAGE: '${{ github.event.commits[0].message }}' + # + # We skip/ignore the README.md file in the Wiki folder + # + SKIP_MD: README.md diff --git a/build.gradle b/build.gradle index 37760a9..fb521b6 100644 --- a/build.gradle +++ b/build.gradle @@ -1,8 +1,8 @@ plugins { - id "java" - id "maven-publish" - id "net.minecrell.licenser" version "0.4.1" - id "com.github.johnrengelman.shadow" version "6.0.0" + id "java" + id "maven-publish" + id "net.minecrell.licenser" version "0.4.1" + id "com.github.johnrengelman.shadow" version "6.0.0" } group "me.clip" @@ -11,99 +11,99 @@ version "2.10.8-DEV-${System.getProperty("BUILD_NUMBER")}" description "An awesome placeholder provider!" repositories { - mavenCentral() + mavenCentral() - maven({ url = "https://repo.codemc.org/repository/maven-public" }) - maven({ url = "https://hub.spigotmc.org/nexus/content/repositories/snapshots/" }) + maven({ url = "https://repo.codemc.org/repository/maven-public" }) + maven({ url = "https://hub.spigotmc.org/nexus/content/repositories/snapshots/" }) } dependencies { - implementation "com.google.code.gson:gson:2.8.6" - implementation "org.bstats:bstats-bukkit:1.5" - - compileOnly "org.spigotmc:spigot-api:1.16.1-R0.1-SNAPSHOT" - compileOnly "org.jetbrains:annotations:19.0.0" - - testImplementation "org.openjdk.jmh:jmh-core:1.23" - testImplementation "org.openjdk.jmh:jmh-generator-annprocess:1.23" - - testCompile "org.junit.jupiter:junit-jupiter-engine:5.6.2" - testRuntime "org.junit.jupiter:junit-jupiter-engine:5.6.2" + implementation "com.google.code.gson:gson:2.8.6" + implementation "org.bstats:bstats-bukkit:1.5" + + compileOnly "org.spigotmc:spigot-api:1.16.1-R0.1-SNAPSHOT" + compileOnly "org.jetbrains:annotations:19.0.0" + + testImplementation "org.openjdk.jmh:jmh-core:1.23" + testImplementation "org.openjdk.jmh:jmh-generator-annprocess:1.23" + + testCompile "org.junit.jupiter:junit-jupiter-engine:5.6.2" + testRuntime "org.junit.jupiter:junit-jupiter-engine:5.6.2" } processResources { - from(sourceSets.main.resources.srcDirs) { - filter org.apache.tools.ant.filters.ReplaceTokens, tokens: [name: rootProject.name, version: project.version.toString(), description: project.description] - } + from(sourceSets.main.resources.srcDirs) { + filter org.apache.tools.ant.filters.ReplaceTokens, tokens: [name: rootProject.name, version: project.version.toString(), description: project.description] + } } tasks.withType(JavaCompile) { - options.encoding = "UTF-8" - - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 + options.encoding = "UTF-8" + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 } shadowJar { - archiveClassifier.set("") + archiveClassifier.set("") - relocate "org.bstats", "me.clip.placeholderapi.metrics" - relocate "com.google.gson", "me.clip.placeholderapi.libs.gson" + relocate "org.bstats", "me.clip.placeholderapi.metrics" + relocate "com.google.gson", "me.clip.placeholderapi.libs.gson" } license { - include '**/*.java' + include '**/*.java' - matching('**/*.java') { - header = file('headers/main.txt') - } + matching('**/*.java') { + header = file('headers/main.txt') + } - matching('**/JSONMessage.java') { - header = file('headers/jsonmessage.txt') - } + matching('**/JSONMessage.java') { + header = file('headers/jsonmessage.txt') + } - ext { - year = 2020 - } + ext { + year = 2020 + } } test { - useJUnitPlatform() + useJUnitPlatform() } sourceSets { - test.compileClasspath += configurations.compileOnly - test.runtimeClasspath += configurations.compileOnly + test.compileClasspath += configurations.compileOnly + test.runtimeClasspath += configurations.compileOnly } publishing { - repositories { - maven { - if (version.contains("-DEV-")) { - url = uri("https://repo.extendedclip.com/content/repositories/dev/") - } else { - url = uri("https://repo.extendedclip.com/content/repositories/placeholderapi/") - } + repositories { + maven { + if (version.contains("-DEV-")) { + url = uri("https://repo.extendedclip.com/content/repositories/dev/") + } else { + url = uri("https://repo.extendedclip.com/content/repositories/placeholderapi/") + } - credentials { - username = System.getenv("JENKINS_USER") - password = System.getenv("JENKINS_PASS") - } - } - } - - publications { - mavenJava(MavenPublication) { - artifactId = "placeholderapi" + credentials { + username = System.getenv("JENKINS_USER") + password = System.getenv("JENKINS_PASS") + } + } + } - from components.java + publications { + mavenJava(MavenPublication) { + artifactId = "placeholderapi" - pom.withXml { - asNode().appendNode("packaging", "jar") - asNode().remove(asNode().get("dependencies")) - } - } - } + from components.java + + pom.withXml { + asNode().appendNode("packaging", "jar") + asNode().remove(asNode().get("dependencies")) + } + } + } } publish.dependsOn clean, test, jar \ No newline at end of file diff --git a/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java b/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java index c81d407..7152e6e 100644 --- a/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java +++ b/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java @@ -220,16 +220,15 @@ public final class PlaceholderAPI { * * @return Map of registered placeholders * @deprecated Use {@link me.clip.placeholderapi.PlaceholderAPIPlugin().getLocalExpansionManager() - * .getExpansions()} instead. + * .getExpansions()} instead. */ @NotNull @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2.11.0") - public static Map getPlaceholders() - { + public static Map getPlaceholders() { return PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() .getExpansions().stream() - .collect(Collectors.toMap(PlaceholderExpansion::getIdentifier, ex -> ex)); + .collect(Collectors.toMap(PlaceholderExpansion::getIdentifier, ex -> ex)); } /** diff --git a/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java b/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java index 32a2f74..fe07931 100644 --- a/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java +++ b/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java @@ -20,6 +20,10 @@ package me.clip.placeholderapi; +import java.text.SimpleDateFormat; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; import me.clip.placeholderapi.commands.PlaceholderCommandRouter; import me.clip.placeholderapi.configuration.PlaceholderAPIConfig; import me.clip.placeholderapi.expansion.PlaceholderExpansion; @@ -36,243 +40,200 @@ import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.NotNull; -import java.text.SimpleDateFormat; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; - /** * Yes I have a shit load of work to do... * * @author Ryan McCarthy */ -public final class PlaceholderAPIPlugin extends JavaPlugin -{ +public final class PlaceholderAPIPlugin extends JavaPlugin { - @NotNull - private static final Version VERSION; + @NotNull + private static final Version VERSION; + private static PlaceholderAPIPlugin instance; - static - { - final String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; + static { + final String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; - boolean isSpigot; - try - { - Class.forName("org.spigotmc.SpigotConfig"); - isSpigot = true; - } - catch (final ExceptionInInitializerError | ClassNotFoundException ignored) - { - isSpigot = false; - } + boolean isSpigot; + try { + Class.forName("org.spigotmc.SpigotConfig"); + isSpigot = true; + } catch (final ExceptionInInitializerError | ClassNotFoundException ignored) { + isSpigot = false; + } - VERSION = new Version(version, isSpigot); - } + VERSION = new Version(version, isSpigot); + } - private static PlaceholderAPIPlugin instance; + @NotNull + private final PlaceholderAPIConfig config = new PlaceholderAPIConfig(this); - @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 LocalExpansionManager localExpansionManager = new LocalExpansionManager(this); - @NotNull - private final CloudExpansionManager cloudExpansionManager = new CloudExpansionManager(this); + /** + * 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(); + } - @Override - public void onLoad() - { - instance = this; + /** + * 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(); + } - saveDefaultConfig(); - } + /** + * 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) { + getInstance().getLogger().log(Level.WARNING, "configured date format is invalid", ex); + return new SimpleDateFormat("MM/dd/yy HH:mm:ss"); + } + } - @Override - public void onEnable() - { - setupCommand(); - setupMetrics(); - setupExpansions(); + public static Version getServerVersion() { + return VERSION; + } - if (config.isCloudEnabled()) - { - getCloudExpansionManager().load(); - } + @Override + public void onLoad() { + instance = this; - if (config.checkUpdates()) - { - new UpdateChecker(this).fetch(); - } - } + saveDefaultConfig(); + } - @Override - public void onDisable() - { - getCloudExpansionManager().kill(); - getLocalExpansionManager().kill(); + @Override + public void onEnable() { + setupCommand(); + setupMetrics(); + setupExpansions(); - HandlerList.unregisterAll(this); + if (config.isCloudEnabled()) { + getCloudExpansionManager().load(); + } - Bukkit.getScheduler().cancelTasks(this); + if (config.checkUpdates()) { + new UpdateChecker(this).fetch(); + } + } - instance = null; - } + @Override + public void onDisable() { + getCloudExpansionManager().kill(); + getLocalExpansionManager().kill(); + HandlerList.unregisterAll(this); - public void reloadConf(@NotNull final CommandSender sender) - { - getLocalExpansionManager().kill(); + Bukkit.getScheduler().cancelTasks(this); - reloadConfig(); + instance = null; + } - getLocalExpansionManager().load(sender); + public void reloadConf(@NotNull final CommandSender sender) { + getLocalExpansionManager().kill(); - if (config.isCloudEnabled()) - { - getCloudExpansionManager().load(); - } - else - { - getCloudExpansionManager().kill(); - } - } + reloadConfig(); + getLocalExpansionManager().load(sender); - @NotNull - public LocalExpansionManager getLocalExpansionManager() - { - return localExpansionManager; - } + if (config.isCloudEnabled()) { + getCloudExpansionManager().load(); + } else { + getCloudExpansionManager().kill(); + } + } - @NotNull - public CloudExpansionManager getCloudExpansionManager() - { - return cloudExpansionManager; - } + @NotNull + public LocalExpansionManager getLocalExpansionManager() { + return localExpansionManager; + } + @NotNull + public CloudExpansionManager getCloudExpansionManager() { + return cloudExpansionManager; + } - /** - * Obtain the configuration class for PlaceholderAPI. - * - * @return PlaceholderAPIConfig instance - */ - @NotNull - public PlaceholderAPIConfig getPlaceholderAPIConfig() - { - return config; - } + /** + * 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; + } - private void setupCommand() - { - final PluginCommand pluginCommand = getCommand("placeholderapi"); - if (pluginCommand == null) - { - return; - } + final PlaceholderCommandRouter router = new PlaceholderCommandRouter(this); + pluginCommand.setExecutor(router); + pluginCommand.setTabCompleter(router); + } - final PlaceholderCommandRouter router = new PlaceholderCommandRouter(this); - pluginCommand.setExecutor(router); - pluginCommand.setTabCompleter(router); - } + private void setupMetrics() { + final Metrics metrics = new Metrics(this); + metrics.addCustomChart(new Metrics.SimplePie("using_expansion_cloud", + () -> getPlaceholderAPIConfig().isCloudEnabled() ? "yes" : "no")); - private void setupMetrics() - { - final Metrics metrics = new Metrics(this); - metrics.addCustomChart(new Metrics.SimplePie("using_expansion_cloud", () -> getPlaceholderAPIConfig().isCloudEnabled() ? "yes" : "no")); + metrics.addCustomChart( + new Metrics.SimplePie("using_spigot", () -> getServerVersion().isSpigot() ? "yes" : "no")); - metrics.addCustomChart(new Metrics.SimplePie("using_spigot", () -> getServerVersion().isSpigot() ? "yes" : "no")); + metrics.addCustomChart(new Metrics.AdvancedPie("expansions_used", () -> { + final Map values = new HashMap<>(); - metrics.addCustomChart(new Metrics.AdvancedPie("expansions_used", () -> { - final Map values = new HashMap<>(); + for (final PlaceholderExpansion expansion : getLocalExpansionManager().getExpansions()) { + values.put(expansion.getRequiredPlugin() == null ? expansion.getIdentifier() + : expansion.getRequiredPlugin(), 1); + } - for (final PlaceholderExpansion expansion : getLocalExpansionManager().getExpansions()) - { - values.put(expansion.getRequiredPlugin() == null ? expansion.getIdentifier() : expansion.getRequiredPlugin(), 1); - } + return values; + })); + } - return values; - })); - } + private void setupExpansions() { + Bukkit.getPluginManager().registerEvents(getLocalExpansionManager(), this); - private void setupExpansions() - { - Bukkit.getPluginManager().registerEvents(getLocalExpansionManager(), this); - - try - { - Class.forName("org.bukkit.event.server.ServerLoadEvent"); - new ServerLoadEventListener(this); - } - catch (final ExceptionInInitializerError | ClassNotFoundException ignored) - { - Bukkit.getScheduler().runTaskLater(this, () -> getLocalExpansionManager().load(Bukkit.getConsoleSender()), 1); - } - } - - - /** - * 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) - { - getInstance().getLogger().log(Level.WARNING, "configured date format is invalid", ex); - return new SimpleDateFormat("MM/dd/yy HH:mm:ss"); - } - } - - - public static Version getServerVersion() - { - return VERSION; - } + try { + Class.forName("org.bukkit.event.server.ServerLoadEvent"); + new ServerLoadEventListener(this); + } catch (final ExceptionInInitializerError | ClassNotFoundException ignored) { + Bukkit.getScheduler() + .runTaskLater(this, () -> 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 0b045a9..72b1be2 100644 --- a/src/main/java/me/clip/placeholderapi/PlaceholderHook.java +++ b/src/main/java/me/clip/placeholderapi/PlaceholderHook.java @@ -27,33 +27,31 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** - * @deprecated This class will be completely removed in the next release, please use {@link me.clip.placeholderapi.expansion.PlaceholderExpansion} + * @deprecated This class will be completely removed in the next release, please use {@link + * me.clip.placeholderapi.expansion.PlaceholderExpansion} */ @Deprecated @ApiStatus.NonExtendable @ApiStatus.ScheduledForRemoval(inVersion = "2.11.0") -public abstract class PlaceholderHook -{ +public abstract class PlaceholderHook { - @Nullable - public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params) - { - if (player != null && player.isOnline()) - { - return onPlaceholderRequest((Player) player, params); - } + @Nullable + public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params) { + if (player != null && player.isOnline()) { + return onPlaceholderRequest((Player) player, params); + } - return onPlaceholderRequest(null, params); - } + return onPlaceholderRequest(null, params); + } - /** - * @deprecated This method will be completely removed, please use {@link me.clip.placeholderapi.expansion.PlaceholderExpansion#onRequest(OfflinePlayer, String)} - */ - @Nullable - @Deprecated - public String onPlaceholderRequest(@Nullable final Player player, @NotNull final String params) - { - return null; - } + /** + * @deprecated This method will be completely removed, please use {@link + * me.clip.placeholderapi.expansion.PlaceholderExpansion#onRequest(OfflinePlayer, String)} + */ + @Nullable + @Deprecated + public String onPlaceholderRequest(@Nullable final Player player, @NotNull final String params) { + return null; + } } diff --git a/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java b/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java index 6497824..016a37c 100644 --- a/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java +++ b/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java @@ -22,97 +22,86 @@ package me.clip.placeholderapi.commands; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; +import java.util.List; +import java.util.Set; +import java.util.stream.Stream; import me.clip.placeholderapi.PlaceholderAPIPlugin; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; -import java.util.Set; -import java.util.stream.Stream; +public abstract class PlaceholderCommand { -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); - } + 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())); + } - @NotNull - public final String getLabel() - { - return label; - } + 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().startsWith(parameter.toLowerCase())) + .forEach(suggestions::add); + } + } - @NotNull - @Unmodifiable - public final Set getAlias() - { - return ImmutableSet.copyOf(alias); - } + @NotNull + public final String getLabel() { + return label; + } - @NotNull - @Unmodifiable - public final Set getLabels() - { - return ImmutableSet.builder().add(label).addAll(alias).build(); - } + @NotNull + @Unmodifiable + public final Set getAlias() { + return ImmutableSet.copyOf(alias); + } + @NotNull + @Unmodifiable + public final Set getLabels() { + return ImmutableSet.builder().add(label).addAll(alias).build(); + } - @Nullable - public final String getPermission() - { - return permission; - } + @Nullable + public final String getPermission() { + return permission; + } - public void setPermission(@NotNull final String permission) - { - this.permission = permission; - } + public void setPermission(@NotNull final String permission) { + this.permission = permission; + } + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { - 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) { - public void complete(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List params, @NotNull final List suggestions) - { - - } - - - @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().startsWith(parameter.toLowerCase())).forEach(suggestions::add); - } - } + } } diff --git a/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java b/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java index 8e0e26f..3c32314 100644 --- a/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java +++ b/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java @@ -22,6 +22,13 @@ 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; +import java.util.Collections; +import java.util.List; +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; @@ -41,103 +48,95 @@ import org.bukkit.command.TabCompleter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.*; -import java.util.stream.Stream; +public final class PlaceholderCommandRouter implements CommandExecutor, TabCompleter { -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(); - final PlaceholderCommand target = commands.get(search); + final String search = args[0].toLowerCase(); + final PlaceholderCommand target = commands.get(search); - if (target == null) - { - Msg.msg(sender, "&cUnknown command &7" + search); - return true; - } + 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; - } + 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))); + target + .evaluate(plugin, sender, search, Arrays.asList(Arrays.copyOfRange(args, 1, args.length))); - return true; - } + 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<>(); + @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()); + if (args.length > 1) { + final PlaceholderCommand target = this.commands.get(args[0].toLowerCase()); - if (target != null) - { - target.complete(plugin, sender, args[0].toLowerCase(), Arrays.asList(Arrays.copyOfRange(args, 1, args.length)), suggestions); - } + if (target != null) { + target.complete(plugin, sender, args[0].toLowerCase(), + Arrays.asList(Arrays.copyOfRange(args, 1, args.length)), suggestions); + } - return 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]); + 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; - } + return suggestions; + } } 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 347f9ba..7a89a34 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 @@ -22,6 +22,10 @@ package me.clip.placeholderapi.commands.impl.cloud; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.util.Msg; @@ -29,126 +33,117 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; +public final class CommandECloud extends PlaceholderCommand { -public final class CommandECloud extends PlaceholderCommand -{ + @Unmodifiable + private static final List COMMANDS = ImmutableList + .of(new CommandECloudClear(), + new CommandECloudToggle(), + 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 CommandECloudToggle(), - new CommandECloudStatus(), - new CommandECloudUpdate(), - new CommandECloudRefresh(), - new CommandECloudDownload(), - new CommandECloudExpansionInfo(), - new CommandECloudExpansionList(), - new CommandECloudExpansionPlaceholders()); + static { + COMMANDS + .forEach(command -> command.setPermission("placeholderapi.ecloud." + command.getLabel())); + } - static - { - COMMANDS.forEach(command -> command.setPermission("placeholderapi.ecloud." + command.getLabel())); - } - - @NotNull - @Unmodifiable - private final Map commands; + @NotNull + @Unmodifiable + private final Map commands; - public CommandECloud() - { - super("ecloud"); + public CommandECloud() { + super("ecloud"); - 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 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 &fenable/disable/toggle", - " &7&oEnable or disable the eCloud", - "&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."); + @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 &fenable/disable/toggle", + " &7&oEnable or disable the eCloud", + "&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; - } + return; + } - final String search = params.get(0).toLowerCase(); - final PlaceholderCommand target = commands.get(search); + final String search = params.get(0).toLowerCase(); + final PlaceholderCommand target = commands.get(search); - if (target == null) - { - Msg.msg(sender, "&cUnknown command &7ecloud " + search); - return; - } + 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; - } + 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 (!(target instanceof CommandECloudToggle) && !plugin.getPlaceholderAPIConfig().isCloudEnabled()) - { - Msg.msg(sender, - "&cThe eCloud Manager is not enabled!"); - return; - } + if (!(target instanceof CommandECloudToggle) && !plugin.getPlaceholderAPIConfig() + .isCloudEnabled()) { + Msg.msg(sender, + "&cThe eCloud Manager is not enabled!"); + return; + } - target.evaluate(plugin, sender, search, params.subList(1, params.size())); - } + 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)); + @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 - } + return; // send sub commands + } - final String search = params.get(0).toLowerCase(); - final PlaceholderCommand target = commands.get(search); + final String search = params.get(0).toLowerCase(); + final PlaceholderCommand target = commands.get(search); - if (target == null) - { - return; - } + if (target == null) { + return; + } - target.complete(plugin, sender, search, params.subList(1, params.size()), suggestions); - } + 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 a87ce91..251ae43 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 @@ -20,6 +20,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; @@ -27,22 +28,19 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; +public final class CommandECloudClear extends PlaceholderCommand { -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 543a72a..7bbb872 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 @@ -20,6 +20,9 @@ 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; @@ -28,98 +31,89 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; -import java.util.Optional; -import java.util.stream.Stream; +public final class CommandECloudDownload extends PlaceholderCommand { -public final class CommandECloudDownload extends PlaceholderCommand -{ + public CommandECloudDownload() { + super("download"); + } - public CommandECloudDownload() - { - super("download"); - } + @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; + } - @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; - } + 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; + } - 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; - } + 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; + } + } - 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; + } - 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!"); - 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().clean(); + plugin.getCloudExpansionManager() + .fetch(plugin.getPlaceholderAPIConfig().cloudAllowUnverifiedExpansions()); + }); + } - plugin.getCloudExpansionManager().clean(); - plugin.getCloudExpansionManager().fetch(plugin.getPlaceholderAPIConfig().cloudAllowUnverifiedExpansions()); - }); - } + @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; + } - @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; + } - 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; + } - final Optional expansion = plugin.getCloudExpansionManager().findCloudExpansionByName(params.get(0)); - if (!expansion.isPresent()) - { - return; - } - - suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1)); - } + 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 1d21d4e..569c0ce 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 @@ -20,6 +20,9 @@ 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; @@ -28,109 +31,99 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; -import java.util.Optional; -import java.util.stream.Stream; +public final class CommandECloudExpansionInfo extends PlaceholderCommand { -public final class CommandECloudExpansionInfo extends PlaceholderCommand -{ + public CommandECloudExpansionInfo() { + super("info"); + } - 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; + } - @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 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(); - 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'); - 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; + } - 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'); + } - 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()); + } - 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; + } - @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; + } - 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; + } - final Optional expansion = plugin.getCloudExpansionManager().findCloudExpansionByName(params.get(0)); - if (!expansion.isPresent()) - { - return; - } - - suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1)); - } + 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 373901e..e4cb193 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,6 +25,19 @@ 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.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +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; @@ -39,322 +52,297 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.IntStream; +public final class CommandECloudExpansionList extends PlaceholderCommand { -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"); - } + public CommandECloudExpansionList() { + super("list"); + } - @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; - } + @NotNull + private static Collection getExpansions(@NotNull final String target, + @NotNull final PlaceholderAPIPlugin plugin) { + switch (target.toLowerCase()) { + 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); - final boolean installed = params.get(0).equalsIgnoreCase("installed"); - final List expansions = Lists.newArrayList(getExpansions(params.get(0), plugin)); + if (expansions.size() < head) { + return Collections.emptyList(); + } - if (expansions.isEmpty()) - { - Msg.msg(sender, - "&cNo expansions available to list."); - return; - } + return expansions.subList(head, tail); + } - expansions.sort(plugin.getPlaceholderAPIConfig().getExpansionSort().orElse(ExpansionSort.LATEST)); + public static void addExpansionTitle(@NotNull final StringBuilder builder, + @NotNull final String target, final int page) { + switch (target.toLowerCase()) { + case "all": + builder.append("&bAll Expansions"); + break; + case "installed": + builder.append("&bInstalled Expansions"); + break; + default: + builder.append("&bExpansions by &f") + .append(target); + break; + } - if (!(sender instanceof Player) && params.size() < 2) - { - final StringBuilder builder = new StringBuilder(); + if (page == -1) { + builder.append('\n'); + return; + } - addExpansionTitle(builder, params.get(0), -1); - addExpansionTable(expansions, - builder, - 1, - installed ? "&9Version" : "&9Latest Version", - installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); + builder.append(" &bPage&7: &a") + .append(page) + .append("&r") + .append('\n'); + } - Msg.msg(sender, builder.toString()); - return; - } + @NotNull + private static JSONMessage getMessage(@NotNull final List expansions, + final int page, final int limit, @NotNull final String target) { + final SimpleDateFormat format = PlaceholderAPIPlugin.getDateFormat(); - final int page; + final StringBuilder tooltip = new StringBuilder(); + final JSONMessage message = JSONMessage.create(); - 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; - } + for (int index = 0; index < expansions.size(); index++) { + final CloudExpansion expansion = expansions.get(index); - final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); + tooltip.append("&bClick to download this expansion!") + .append('\n') + .append('\n') + .append("&bAuthor: &f") + .append(expansion.getAuthor()) + .append('\n') + .append("&bVerified: ") + .append(expansion.isVerified() ? "&a&l✔&r" : "&c&l❌&r") + .append('\n') + .append("&bLatest Version: &f") + .append(expansion.getLatestVersion()) + .append('\n') + .append("&bReleased: &f") + .append(format.format(expansion.getLastUpdate())); - if (parsed < 1 || parsed > limit) - { - Msg.msg(sender, - "&cPage number must be in the range &8[&a1&7..&a" + limit + "&8]"); - return; - } + final String description = expansion.getDescription(); + if (description != null && !description.isEmpty()) { + tooltip.append('\n') + .append('\n') + .append("&f") + .append(description.replace("\r", "").trim()); + } - page = parsed; - } + message.then(Msg.color( + "&8" + (index + ((page - 1) * PAGE_SIZE) + 1) + ".&r " + (expansion.shouldUpdate() ? "&6" + : expansion.hasExpansion() ? "&a" : "&7") + expansion.getName())); - final StringBuilder builder = new StringBuilder(); - final List values = getPage(expansions, page - 1); + message.tooltip(Msg.color(tooltip.toString())); + message.suggestCommand("/papi ecloud download " + expansion.getName()); - addExpansionTitle(builder, params.get(0), page); + if (index < expansions.size() - 1) { + message.newline(); + } - if (!(sender instanceof Player)) - { - addExpansionTable(values, - builder, - ((page - 1) * PAGE_SIZE) + 1, - installed ? "&9Version" : "&9Latest Version", - installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); + tooltip.setLength(0); + } - Msg.msg(sender, builder.toString()); + if (limit > 1) { + message.newline(); - return; - } + message.then("◀") + .color(page > 1 ? ChatColor.GRAY : ChatColor.DARK_GRAY); + if (page > 1) { + message.runCommand("/papi ecloud list " + target + " " + (page - 1)); + } - Msg.msg(sender, builder.toString()); + message.then(" " + page + " ").color(ChatColor.GREEN); - final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); + message.then("▶") + .color(page < limit ? ChatColor.GRAY : ChatColor.DARK_GRAY); + if (page < limit) { + message.runCommand("/papi ecloud list " + target + " " + (page + 1)); + } + } - final JSONMessage message = getMessage(values, page, limit, params.get(0)); - message.send(((Player) sender)); - } + return 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; - } + 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 (params.size() <= 1) - { - suggestByParameter(Sets.union(OPTIONS, plugin.getCloudExpansionManager().getCloudExpansionAuthors()).stream(), suggestions, params.isEmpty() ? null : params.get(0)); - return; - } + final AtomicInteger counter = new AtomicInteger(startIndex); + functions.put("&f", expansion -> "&8" + counter.getAndIncrement() + "."); - suggestByParameter(IntStream.rangeClosed(1, (int) Math.ceil((double) getExpansions(params.get(0), plugin).size() / PAGE_SIZE)).mapToObj(Objects::toString), suggestions, params.get(1)); - } + functions.put("&9Name", EXPANSION_NAME); + functions.put("&9Author", EXPANSION_AUTHOR); + functions.put("&9Verified", EXPANSION_VERIFIED); + functions.put(versionTitle, versionFunction); + final List> rows = new ArrayList<>(); - @NotNull - private static Collection getExpansions(@NotNull final String target, @NotNull final PlaceholderAPIPlugin plugin) - { - switch (target.toLowerCase()) - { - case "all": - return plugin.getCloudExpansionManager().getCloudExpansions().values(); - case "installed": - return plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values(); - default: - return plugin.getCloudExpansionManager().getCloudExpansionsByAuthor(target).values(); - } - } + rows.add(0, new ArrayList<>(functions.keySet())); - @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); + for (final CloudExpansion expansion : expansions) { + rows.add(functions.values().stream().map(function -> function.apply(expansion)) + .map(Objects::toString).collect(Collectors.toList())); + } - if (expansions.size() < head) - { - return Collections.emptyList(); - } + final List table = Format.tablify(Format.Align.LEFT, rows) + .orElse(Collections.emptyList()); + if (table.isEmpty()) { + return; + } - return expansions.subList(head, tail); - } + table.add(1, "&8" + Strings.repeat("-", table.get(0).length() - (rows.get(0).size() * 2))); - public static void addExpansionTitle(@NotNull final StringBuilder builder, @NotNull final String target, final int page) - { - switch (target.toLowerCase()) - { - case "all": - builder.append("&bAll Expansions"); - break; - case "installed": - builder.append("&bInstalled Expansions"); - break; - default: - builder.append("&bExpansions by &f") - .append(target); - break; - } + message.append(String.join("\n", table)); + } - if (page == -1) - { - builder.append('\n'); - 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 an option. [all, {author}, installed]"); + return; + } - builder.append(" &bPage&7: &a") - .append(page) - .append("&r") - .append('\n'); - } + 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; + } - @NotNull - private static JSONMessage getMessage(@NotNull final List expansions, final int page, final int limit, @NotNull final String target) - { - final SimpleDateFormat format = PlaceholderAPIPlugin.getDateFormat(); + expansions + .sort(plugin.getPlaceholderAPIConfig().getExpansionSort().orElse(ExpansionSort.LATEST)); - final StringBuilder tooltip = new StringBuilder(); - final JSONMessage message = JSONMessage.create(); + if (!(sender instanceof Player) && params.size() < 2) { + final StringBuilder builder = new StringBuilder(); - for (int index = 0; index < expansions.size(); index++) - { - final CloudExpansion expansion = expansions.get(index); + addExpansionTitle(builder, params.get(0), -1); + addExpansionTable(expansions, + builder, + 1, + installed ? "&9Version" : "&9Latest Version", + installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); - tooltip.append("&bClick to download this expansion!") - .append('\n') - .append('\n') - .append("&bAuthor: &f") - .append(expansion.getAuthor()) - .append('\n') - .append("&bVerified: ") - .append(expansion.isVerified() ? "&a&l✔&r" : "&c&l❌&r") - .append('\n') - .append("&bLatest Version: &f") - .append(expansion.getLatestVersion()) - .append('\n') - .append("&bReleased: &f") - .append(format.format(expansion.getLastUpdate())); + Msg.msg(sender, builder.toString()); + return; + } - final String description = expansion.getDescription(); - if (description != null && !description.isEmpty()) - { - tooltip.append('\n') - .append('\n') - .append("&f") - .append(description.replace("\r", "").trim()); - } + final int page; - message.then(Msg.color("&8" + (index + ((page - 1) * PAGE_SIZE) + 1) + ".&r " + (expansion.shouldUpdate() ? "&6" : expansion.hasExpansion() ? "&a" : "&7") + expansion.getName())); + 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; + } - message.tooltip(Msg.color(tooltip.toString())); - message.suggestCommand("/papi ecloud download " + expansion.getName()); + final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); - if (index < expansions.size() - 1) - { - message.newline(); - } + if (parsed < 1 || parsed > limit) { + Msg.msg(sender, + "&cPage number must be in the range &8[&a1&7..&a" + limit + "&8]"); + return; + } - tooltip.setLength(0); - } + page = parsed; + } - if (limit > 1) - { - message.newline(); + final StringBuilder builder = new StringBuilder(); + final List values = getPage(expansions, page - 1); - message.then("◀") - .color(page > 1 ? ChatColor.GRAY : ChatColor.DARK_GRAY); - if (page > 1) - { - message.runCommand("/papi ecloud list " + target + " " + (page - 1)); - } + addExpansionTitle(builder, params.get(0), page); - message.then(" " + page + " ").color(ChatColor.GREEN); + if (!(sender instanceof Player)) { + addExpansionTable(values, + builder, + ((page - 1) * PAGE_SIZE) + 1, + installed ? "&9Version" : "&9Latest Version", + installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); - message.then("▶") - .color(page < limit ? ChatColor.GRAY : ChatColor.DARK_GRAY); - if (page < limit) - { - message.runCommand("/papi ecloud list " + target + " " + (page + 1)); - } - } + Msg.msg(sender, builder.toString()); - return message; - } + return; + } - 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<>(); + Msg.msg(sender, builder.toString()); - final AtomicInteger counter = new AtomicInteger(startIndex); - functions.put("&f", expansion -> "&8" + counter.getAndIncrement() + "."); + final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); - functions.put("&9Name", EXPANSION_NAME); - functions.put("&9Author", EXPANSION_AUTHOR); - functions.put("&9Verified", EXPANSION_VERIFIED); - functions.put(versionTitle, versionFunction); + final JSONMessage message = getMessage(values, page, limit, params.get(0)); + message.send(((Player) sender)); + } - final List> rows = new ArrayList<>(); + @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; + } - rows.add(0, new ArrayList<>(functions.keySet())); + if (params.size() <= 1) { + suggestByParameter( + Sets.union(OPTIONS, plugin.getCloudExpansionManager().getCloudExpansionAuthors()) + .stream(), suggestions, params.isEmpty() ? null : params.get(0)); + return; + } - 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)); - } + 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 f94ac22..9d51966 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,6 +21,9 @@ 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; @@ -29,68 +32,63 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; +public final class CommandECloudExpansionPlaceholders extends PlaceholderCommand { -public final class CommandECloudExpansionPlaceholders extends PlaceholderCommand -{ + public CommandECloudExpansionPlaceholders() { + super("placeholders"); + } - 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; + } - @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 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 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); - 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"))); - 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; + } - @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(' ', '_')); - final Stream names = plugin.getCloudExpansionManager() - .getCloudExpansions() - .values() - .stream() - .map(CloudExpansion::getName) - .map(name -> name.replace(' ', '_')); - - suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); - } + 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 148e73d..2185d88 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 @@ -20,6 +20,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; @@ -27,24 +28,22 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; +public final class CommandECloudRefresh extends PlaceholderCommand { -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().clean(); + plugin.getCloudExpansionManager() + .fetch(plugin.getPlaceholderAPIConfig().cloudAllowUnverifiedExpansions()); - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List params) - { - plugin.getCloudExpansionManager().clean(); - plugin.getCloudExpansionManager().fetch(plugin.getPlaceholderAPIConfig().cloudAllowUnverifiedExpansions()); - - 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 bbbc921..47aafa6 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 @@ -20,6 +20,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; @@ -28,36 +29,36 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; +public final class CommandECloudStatus extends PlaceholderCommand { -public final class CommandECloudStatus extends PlaceholderCommand -{ + public CommandECloudStatus() { + super("status"); + } - 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(); - @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 int updateCount = manager.getCloudUpdateCount(); - final int authorCount = manager.getCloudExpansionAuthorCount(); - final int expansionCount = manager.getCloudExpansions().size(); + final StringBuilder builder = new StringBuilder(); - 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'); - 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."); + } - 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()); - } + Msg.msg(sender, builder.toString()); + } } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudToggle.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudToggle.java index 3dd211d..5cbd754 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudToggle.java +++ b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudToggle.java @@ -20,6 +20,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; @@ -27,53 +28,45 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; +public final class CommandECloudToggle extends PlaceholderCommand { -public final class CommandECloudToggle extends PlaceholderCommand -{ + public CommandECloudToggle() { + super("toggle", "enable", "disable"); + } - public CommandECloudToggle() - { - super("toggle", "enable", "disable"); - } + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + final boolean desiredState; + final boolean currentState = plugin.getPlaceholderAPIConfig().isCloudEnabled(); - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List params) - { - final boolean desiredState; - final boolean currentState = plugin.getPlaceholderAPIConfig().isCloudEnabled(); + switch (alias.toLowerCase()) { + case "enable": + desiredState = true; + break; + case "disable": + desiredState = false; + break; + default: + desiredState = !currentState; + break; + } - switch (alias.toLowerCase()) - { - case "enable": - desiredState = true; - break; - case "disable": - desiredState = false; - break; - default: - desiredState = !currentState; - break; - } + if (desiredState == currentState) { + Msg.msg(sender, "&7The eCloud Manager is already " + (desiredState ? "enabled" : "disabled")); + return; + } - if (desiredState == currentState) - { - Msg.msg(sender, "&7The eCloud Manager is already " + (desiredState ? "enabled" : "disabled")); - return; - } + plugin.getPlaceholderAPIConfig().setCloudEnabled(desiredState); - plugin.getPlaceholderAPIConfig().setCloudEnabled(desiredState); + if (desiredState) { + plugin.getCloudExpansionManager().load(); + } else { + plugin.getCloudExpansionManager().kill(); + } - if (desiredState) - { - plugin.getCloudExpansionManager().load(); - } - else - { - plugin.getCloudExpansionManager().kill(); - } - - Msg.msg(sender, "&aThe eCloud Manager has been " + (desiredState ? "enabled" : "disabled")); - } + Msg.msg(sender, "&aThe eCloud Manager has been " + (desiredState ? "enabled" : "disabled")); + } } 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 2e94c6b..6b4d21a 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,12 @@ package me.clip.placeholderapi.commands.impl.cloud; import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.List; +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; @@ -32,114 +38,103 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Unmodifiable; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; - /** * please don't flame me for this code, I will fix this shit later. */ -public final class CommandECloudUpdate extends PlaceholderCommand -{ +public final class CommandECloudUpdate extends PlaceholderCommand { - public CommandECloudUpdate() - { - super("update"); - } + 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; - } + @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; + } - final boolean multiple = params.get(0).equalsIgnoreCase("all"); - final List expansions = new ArrayList<>(); + 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); - } + // 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()); + // 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; - } + if (expansions.isEmpty()) { + Msg.msg(sender, + "&cNo updates available for " + (!multiple ? "this expansion." + : "your active expansions.")); + return; + } - Msg.msg(sender, - "&aUpdating expansions: " + expansions.stream().map(CloudExpansion::getName).collect(Collectors.joining("&7, &6", "&8[&6", "&8]&r"))); + Msg.msg(sender, + "&aUpdating expansions: " + expansions.stream().map(CloudExpansion::getName) + .collect(Collectors.joining("&7, &6", "&8[&6", "&8]&r"))); + Futures.onMainThread(plugin, downloadAndDiscover(expansions, plugin), (classes, exception) -> { + if (exception != null) { + Msg.msg(sender, + "&cFailed to update expansions: &e" + exception.getMessage()); + return; + } - Futures.onMainThread(plugin, downloadAndDiscover(expansions, plugin), (classes, exception) -> { - if (exception != null) - { - Msg.msg(sender, - "&cFailed to update expansions: &e" + exception.getMessage()); - return; - } + Msg.msg(sender, + "&aSuccessfully downloaded updates, registering new versions."); - Msg.msg(sender, - "&aSuccessfully downloaded updates, registering new versions."); + 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); - 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()))) { + 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()))) - { - suggestions.add("all"); - } - - suggestByParameter(installed.stream().map(CloudExpansion::getName).map(name -> name.replace(" ", "_")), suggestions, params.isEmpty() ? null : params.get(0)); - } - - - 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()); - } + 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 551703c..d3c3637 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 @@ -22,15 +22,6 @@ package me.clip.placeholderapi.commands.impl.local; import com.google.common.io.CharStreams; import com.google.gson.JsonParser; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.CommandSender; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -50,164 +41,165 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.logging.Level; import java.util.stream.Collectors; +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; -public final class CommandDump extends PlaceholderCommand -{ - - @NotNull - private static final String URL = "https://paste.helpch.at/"; - - @NotNull - private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG) - .withLocale(Locale.US) - .withZone(ZoneId.of("UTC")); - - - 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); - - Msg.msg(sender, - "&cFailed to post dump details, check console."); - return; - } - - 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); - - connection.connect(); - - try (final OutputStream stream = connection.getOutputStream()) - { - stream.write(dump.getBytes(StandardCharsets.UTF_8)); - } - - try (final InputStream stream = connection.getInputStream()) - { - //noinspection UnstableApiUsage - final String json = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8)); - return JsonParser.parseString(json).getAsJsonObject().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)) - .sorted(Comparator.comparing(PlaceholderExpansion::getAuthor)) - .collect(Collectors.toList()); - - int size = 0; - - for(final String name : expansions.stream().map(PlaceholderExpansion::getIdentifier).collect(Collectors.toList())){ - if (name.length() > size) { - size = name.length(); - } - } - - 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"); - - } - - builder.append('\n'); - - builder.append("Expansions Directory:") - .append('\n'); - - final String[] jars = plugin.getLocalExpansionManager() - .getExpansionsFolder() - .list((dir, name) -> name.toLowerCase().endsWith(".jar")); - - 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\n"); - - builder.append("Plugin Info:") - .append('\n'); - - List plugins = Arrays.stream(plugin.getServer().getPluginManager().getPlugins()) - .sorted(Comparator.comparing(Plugin::getName)) - .collect(Collectors.toList()); - - for (final String pluginName : plugins.stream().map(Plugin::getName).collect(Collectors.toList())) { - if (pluginName.length() > size) { - size = pluginName.length(); - } - } - - for (final Plugin other : plugins) - { - builder.append(" ") - .append(String.format("%-" + size + "s", other.getName())) - .append(" [Version: ") - .append(other.getDescription().getVersion()) - .append("]") - .append("\n"); - } - - return builder.toString(); - } +public final class CommandDump extends PlaceholderCommand { + + @NotNull + private static final String URL = "https://paste.helpch.at/"; + + @NotNull + private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter + .ofLocalizedDateTime(FormatStyle.LONG) + .withLocale(Locale.US) + .withZone(ZoneId.of("UTC")); + + + 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); + + Msg.msg(sender, + "&cFailed to post dump details, check console."); + return; + } + + 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); + + connection.connect(); + + try (final OutputStream stream = connection.getOutputStream()) { + stream.write(dump.getBytes(StandardCharsets.UTF_8)); + } + + try (final InputStream stream = connection.getInputStream()) { + //noinspection UnstableApiUsage + final String json = CharStreams + .toString(new InputStreamReader(stream, StandardCharsets.UTF_8)); + return JsonParser.parseString(json).getAsJsonObject().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)) + .sorted(Comparator.comparing(PlaceholderExpansion::getAuthor)) + .collect(Collectors.toList()); + + int size = 0; + + for (final String name : expansions.stream().map(PlaceholderExpansion::getIdentifier) + .collect(Collectors.toList())) { + if (name.length() > size) { + size = name.length(); + } + } + + 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"); + + } + + builder.append('\n'); + + builder.append("Expansions Directory:") + .append('\n'); + + final String[] jars = plugin.getLocalExpansionManager() + .getExpansionsFolder() + .list((dir, name) -> name.toLowerCase().endsWith(".jar")); + + 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\n"); + + builder.append("Plugin Info:") + .append('\n'); + + List plugins = Arrays.stream(plugin.getServer().getPluginManager().getPlugins()) + .sorted(Comparator.comparing(Plugin::getName)) + .collect(Collectors.toList()); + + for (final String pluginName : plugins.stream().map(Plugin::getName) + .collect(Collectors.toList())) { + if (pluginName.length() > size) { + size = pluginName.length(); + } + } + + for (final Plugin other : plugins) { + builder.append(" ") + .append(String.format("%-" + size + "s", other.getName())) + .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 f884c82..84cf1bf 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 @@ -20,6 +20,11 @@ package me.clip.placeholderapi.commands.impl.local; +import java.io.File; +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; @@ -30,88 +35,76 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.io.File; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.logging.Level; +public final class CommandExpansionRegister extends PlaceholderCommand { -public final class CommandExpansionRegister extends PlaceholderCommand -{ + public CommandExpansionRegister() { + super("register"); + } - 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; + } - @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 LocalExpansionManager manager = plugin.getLocalExpansionManager(); + final File file = new File(manager.getExpansionsFolder(), params.get(0)); + if (!file.exists()) { + Msg.msg(sender, + "&cThe file &f" + file.getName() + "&c doesn't exist!"); + return; + } - final LocalExpansionManager manager = plugin.getLocalExpansionManager(); + Futures.onMainThread(plugin, manager.findExpansionInFile(file), (clazz, exception) -> { + if (exception != null) { + Msg.msg(sender, + "&cFailed to find expansion in file: &f" + file); - final File file = new File(manager.getExpansionsFolder(), params.get(0)); - if (!file.exists()) - { - Msg.msg(sender, - "&cThe file &f" + file.getName() + "&c doesn't exist!"); - return; - } + plugin.getLogger() + .log(Level.WARNING, "failed to find expansion in file: " + file, exception); + return; + } - Futures.onMainThread(plugin, manager.findExpansionInFile(file), (clazz, exception) -> { - if (exception != null) - { - Msg.msg(sender, - "&cFailed to find expansion in file: &f" + file); + if (clazz == null) { + Msg.msg(sender, + "&cNo expansion class found in file: &f" + file); + return; + } - plugin.getLogger().log(Level.WARNING, "failed to find expansion in file: " + file, exception); - return; - } + final Optional expansion = manager.register(clazz); + if (!expansion.isPresent()) { + Msg.msg(sender, + "&cFailed to register expansion from &f" + params.get(0)); + return; + } - if (clazz == null) - { - Msg.msg(sender, - "&cNo expansion class found in file: &f" + file); - return; - } + Msg.msg(sender, + "&aSuccessfully registered expansion: &f" + expansion.get().getName()); + }); + } - final Optional expansion = manager.register(clazz); - if (!expansion.isPresent()) - { - Msg.msg(sender, - "&cFailed to register expansion from &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() > 1) { + return; + } - Msg.msg(sender, - "&aSuccessfully registered expansion: &f" + expansion.get().getName()); + final String[] fileNames = plugin.getLocalExpansionManager().getExpansionsFolder() + .list((dir, name) -> name.endsWith(".jar")); + if (fileNames == null || fileNames.length == 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() > 1) - { - return; - } - - 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)); - } + 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 6cd32ed..4b59fac 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 @@ -20,6 +20,8 @@ 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; @@ -29,52 +31,47 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; -import java.util.Optional; +public final class CommandExpansionUnregister extends PlaceholderCommand { -public final class CommandExpansionUnregister extends PlaceholderCommand -{ + public CommandExpansionUnregister() { + super("unregister"); + } - 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; + } - @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 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 ef2b352..d43e2fe 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 @@ -20,6 +20,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; @@ -28,47 +29,44 @@ import org.bukkit.plugin.PluginDescriptionFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; +public final class CommandHelp extends PlaceholderCommand { -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 e86d1a6..11ec7bd 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 @@ -20,6 +20,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; @@ -29,92 +30,84 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; +public final class CommandInfo extends PlaceholderCommand { -public final class CommandInfo extends PlaceholderCommand -{ + public CommandInfo() { + super("info"); + } - 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; + } - @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() + .findExpansionByName(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 PlaceholderExpansion expansion = plugin.getLocalExpansionManager().findExpansionByName(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(); - 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'); - 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 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 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 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'); - 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'); + } + } - for (final String placeholder : placeholders) - { - builder.append(placeholder) - .append('\n'); - } - } + Msg.msg(sender, builder.toString()); + } - 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; + } - @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/CommandList.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandList.java index a2f7bc3..f401e7f 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,6 +21,9 @@ 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; @@ -29,34 +32,30 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; +public final class CommandList extends PlaceholderCommand { -public final class CommandList extends PlaceholderCommand -{ - - public CommandList() - { - super("list"); - } + 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; - } + @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); + 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"))); - } + 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 2c769df..5231ebf 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 @@ -20,6 +20,10 @@ package me.clip.placeholderapi.commands.impl.local; +import java.util.HashSet; +import java.util.List; +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; @@ -34,210 +38,187 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Unmodifiable; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Stream; +public final class CommandParse extends PlaceholderCommand { -public final class CommandParse extends PlaceholderCommand -{ - - public CommandParse() - { - super("parse", "bcparse", "parserel", "cmdparse"); - } + 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()) - { - 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 evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + switch (alias.toLowerCase()) { + 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()) - { - case "parserel": - completeParseRelation(params, suggestions); - break; - case "parse": - case "bcparse": - case "cmdparse": - completeParseSingular(sender, params, suggestions); - 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()) { + 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 supply a target, and a message: &b/papi " + (broadcast ? "bcparse" : "parse") + " &7{target} &a{message}"); - 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 supply a target, and a message: &b/papi " + (broadcast ? "bcparse" : "parse") + + " &7{target} &a{message}"); + return; + } - @NotNull final OfflinePlayer player; + @NotNull final 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; - } + 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 - { - final OfflinePlayer target = resolvePlayer(params.get(0)); - if (target == null) - { - Msg.msg(sender, "&cFailed to find player: &7" + params.get(0)); - return; - } + player = ((Player) sender); + } 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; - } + player = target; + } - final String message = PlaceholderAPI.setPlaceholders(player, String.join(" ", params.subList(1, params.size()))); + final String message = PlaceholderAPI + .setPlaceholders(player, String.join(" ", params.subList(1, params.size()))); - if (command) - { - Bukkit.dispatchCommand(sender, message); - return; - } + if (command) { + Bukkit.dispatchCommand(sender, message); + return; + } - if (broadcast) - { - Msg.broadcast(message); - } - else - { - if (!(sender instanceof Player)) - { - Msg.msg(sender, message); - } - else - { - ((Player) sender).spigot().sendMessage(TextComponent.fromLegacyText(message)); - } - } - } + if (broadcast) { + Msg.broadcast(message); + } else { + if (!(sender instanceof Player)) { + Msg.msg(sender, message); + } else { + ((Player) sender).spigot().sendMessage(TextComponent.fromLegacyText(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; - } + 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; + } - final OfflinePlayer targetOne = resolvePlayer(params.get(0)); - if (targetOne == null || !targetOne.isOnline()) - { - Msg.msg(sender, "&cFailed to find player: &f" + params.get(0)); - return; - } + final OfflinePlayer targetOne = resolvePlayer(params.get(0)); + if (targetOne == null || !targetOne.isOnline()) { + Msg.msg(sender, "&cFailed to find player: &f" + params.get(0)); + return; + } - final OfflinePlayer targetTwo = resolvePlayer(params.get(1)); - if (targetTwo == null || !targetTwo.isOnline()) - { - Msg.msg(sender, "&cFailed to find player: &f" + params.get(1)); - return; - } + final OfflinePlayer targetTwo = resolvePlayer(params.get(1)); + if (targetTwo == null || !targetTwo.isOnline()) { + Msg.msg(sender, "&cFailed to find player: &f" + params.get(1)); + return; + } - final String message = PlaceholderAPI.setRelationalPlaceholders(((Player) targetOne), ((Player) targetTwo), String.join(" ", params.subList(2, params.size()))); - Msg.msg(sender, message); - } + final String message = PlaceholderAPI + .setRelationalPlaceholders(((Player) targetOne), ((Player) targetTwo), + String.join(" ", params.subList(2, params.size()))); + Msg.msg(sender, message); + } - 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()))) - { - suggestions.add("me"); - } + 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()))) { + suggestions.add("me"); + } - final Stream names = Bukkit.getOnlinePlayers().stream().map(Player::getName); - suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); + final Stream names = Bukkit.getOnlinePlayers().stream().map(Player::getName); + suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); - return; - } + return; + } - final String name = params.get(params.size() - 1); - if (!name.startsWith("%") || name.endsWith("%")) - { - 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 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 PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() + .getLocalExpansionManager().findExpansionByIdentifier(name.substring(1, index)) + .orElse(null); + if (expansion == null) { + return; + } - final Set possible = new HashSet<>(expansion.getPlaceholders()); + final Set possible = new HashSet<>(expansion.getPlaceholders()); - PlaceholderAPIPlugin.getInstance() - .getCloudExpansionManager() - .findCloudExpansionByName(expansion.getName()) - .ifPresent(cloud -> possible.addAll(cloud.getPlaceholders())); + PlaceholderAPIPlugin.getInstance() + .getCloudExpansionManager() + .findCloudExpansionByName(expansion.getName()) + .ifPresent(cloud -> possible.addAll(cloud.getPlaceholders())); - suggestByParameter(possible.stream(), suggestions, params.get(params.size() - 1)); - } + 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; - } + 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 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.getPlayer(name); + @Nullable + private OfflinePlayer resolvePlayer(@NotNull final String name) { + OfflinePlayer target = Bukkit.getPlayer(name); - if (target == null) - { - target = Bukkit.getOfflinePlayer(name); // this is probably not a great idea. - } + if (target == null) { + target = Bukkit.getOfflinePlayer(name); // this is probably not a great idea. + } - return target.hasPlayedBefore() ? target : null; + return target.hasPlayedBefore() ? target : null; - } + } } 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 2dc0dc3..5bb6d97 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 @@ -20,26 +20,24 @@ 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; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; +public final class CommandReload extends PlaceholderCommand { -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 ce20860..6804f1c 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 @@ -20,6 +20,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; @@ -28,27 +29,24 @@ import org.bukkit.plugin.PluginDescriptionFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; -import java.util.List; +public final class CommandVersion extends PlaceholderCommand { -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/configuration/ExpansionSort.java b/src/main/java/me/clip/placeholderapi/configuration/ExpansionSort.java index dae101d..c663f47 100644 --- a/src/main/java/me/clip/placeholderapi/configuration/ExpansionSort.java +++ b/src/main/java/me/clip/placeholderapi/configuration/ExpansionSort.java @@ -20,32 +20,28 @@ package me.clip.placeholderapi.configuration; +import java.util.Comparator; import me.clip.placeholderapi.expansion.cloud.CloudExpansion; import org.jetbrains.annotations.NotNull; -import java.util.Comparator; +public enum ExpansionSort implements Comparator { -public enum ExpansionSort implements Comparator -{ - - NAME(Comparator.comparing(CloudExpansion::getName)), - AUTHOR(Comparator.comparing(CloudExpansion::getAuthor)), - LATEST(Comparator.comparing(CloudExpansion::getLastUpdate).reversed()); + NAME(Comparator.comparing(CloudExpansion::getName)), + AUTHOR(Comparator.comparing(CloudExpansion::getAuthor)), + LATEST(Comparator.comparing(CloudExpansion::getLastUpdate).reversed()); - @NotNull - private final Comparator comparator; + @NotNull + private final Comparator comparator; - ExpansionSort(@NotNull final Comparator comparator) - { - this.comparator = comparator; - } + ExpansionSort(@NotNull final Comparator comparator) { + this.comparator = comparator; + } - @Override - public final int compare(final CloudExpansion expansion1, final CloudExpansion expansion2) - { - return comparator.compare(expansion1, expansion2); - } + @Override + public final int compare(final CloudExpansion expansion1, final CloudExpansion expansion2) { + return comparator.compare(expansion1, expansion2); + } } diff --git a/src/main/java/me/clip/placeholderapi/configuration/PlaceholderAPIConfig.java b/src/main/java/me/clip/placeholderapi/configuration/PlaceholderAPIConfig.java index 7a8fbd5..78b728e 100644 --- a/src/main/java/me/clip/placeholderapi/configuration/PlaceholderAPIConfig.java +++ b/src/main/java/me/clip/placeholderapi/configuration/PlaceholderAPIConfig.java @@ -20,88 +20,74 @@ package me.clip.placeholderapi.configuration; +import java.util.Optional; import me.clip.placeholderapi.PlaceholderAPIPlugin; import org.jetbrains.annotations.NotNull; -import java.util.Optional; +public final class PlaceholderAPIConfig { -public final class PlaceholderAPIConfig -{ + @NotNull + private final PlaceholderAPIPlugin plugin; - @NotNull - private final PlaceholderAPIPlugin plugin; - - public PlaceholderAPIConfig(@NotNull final PlaceholderAPIPlugin plugin) - { - this.plugin = plugin; - } + public PlaceholderAPIConfig(@NotNull final PlaceholderAPIPlugin plugin) { + this.plugin = plugin; + } - public boolean checkUpdates() - { - return plugin.getConfig().getBoolean("check_updates"); - } + public boolean checkUpdates() { + return plugin.getConfig().getBoolean("check_updates"); + } - public boolean cloudAllowUnverifiedExpansions() - { - return plugin.getConfig().getBoolean("cloud_allow_unverified_expansions"); - } + public boolean cloudAllowUnverifiedExpansions() { + return plugin.getConfig().getBoolean("cloud_allow_unverified_expansions"); + } - public boolean isCloudEnabled() - { - return plugin.getConfig().getBoolean("cloud_enabled"); - } + public boolean isCloudEnabled() { + return plugin.getConfig().getBoolean("cloud_enabled"); + } - public void setCloudEnabled(boolean state) - { - plugin.getConfig().set("cloud_enabled", state); - plugin.saveConfig(); - } + public void setCloudEnabled(boolean state) { + plugin.getConfig().set("cloud_enabled", state); + plugin.saveConfig(); + } - public boolean isDebugMode() - { - return plugin.getConfig().getBoolean("debug", false); - } + public boolean isDebugMode() { + return plugin.getConfig().getBoolean("debug", false); + } - public Optional getExpansionSort() - { - final String option = plugin.getConfig().getString("cloud_sorting", ExpansionSort.LATEST.name()); + public Optional getExpansionSort() { + final String option = plugin.getConfig() + .getString("cloud_sorting", ExpansionSort.LATEST.name()); - try - { - //noinspection ConstantConditions (bad spigot annotation) - return Optional.of(ExpansionSort.valueOf(option.toUpperCase())); - } - catch (final IllegalArgumentException ignored) - { - return Optional.empty(); - } - } + try { + //noinspection ConstantConditions (bad spigot annotation) + return Optional.of(ExpansionSort.valueOf(option.toUpperCase())); + } catch (final IllegalArgumentException ignored) { + return Optional.empty(); + } + } - @NotNull - public String dateFormat() - { - //noinspection ConstantConditions (bad spigot annotation) - return plugin.getConfig().getString("date_format", "MM/dd/yy HH:mm:ss"); - } + @NotNull + public String dateFormat() { + //noinspection ConstantConditions (bad spigot annotation) + return plugin.getConfig().getString("date_format", "MM/dd/yy HH:mm:ss"); + } - @NotNull - public String booleanTrue() - { - //noinspection ConstantConditions (bad spigot annotation) - return plugin.getConfig().getString("boolean.true", "true"); - } + @NotNull + public String booleanTrue() { + //noinspection ConstantConditions (bad spigot annotation) + return plugin.getConfig().getString("boolean.true", "true"); + } - @NotNull - public String booleanFalse() - { - //noinspection ConstantConditions (bad spigot annotation) - return plugin.getConfig().getString("boolean.false", "false"); - } + @NotNull + public String booleanFalse() { + //noinspection ConstantConditions (bad spigot annotation) + return plugin.getConfig().getString("boolean.false", "false"); + } } diff --git a/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java b/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java index 4a97b06..e1e556f 100644 --- a/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java +++ b/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java @@ -26,55 +26,42 @@ import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; -public final class ExpansionRegisterEvent extends Event implements Cancellable -{ +public final class ExpansionRegisterEvent extends Event implements Cancellable { - @NotNull - private static final HandlerList HANDLERS = new HandlerList(); + @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; + } - private boolean cancelled; - @NotNull - private final PlaceholderExpansion expansion; + @NotNull + public static HandlerList getHandlerList() { + return HANDLERS; + } - public ExpansionRegisterEvent(@NotNull final PlaceholderExpansion expansion) - { - this.expansion = expansion; - } + @NotNull + public PlaceholderExpansion getExpansion() { + return expansion; + } + @Override + public boolean isCancelled() { + return cancelled; + } - @NotNull - public PlaceholderExpansion getExpansion() - { - return expansion; - } + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } - - @Override - public boolean isCancelled() - { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) - { - this.cancelled = cancelled; - } - - - @NotNull - @Override - public HandlerList getHandlers() - { - return HANDLERS; - } - - - @NotNull - public static HandlerList getHandlerList() - { - return HANDLERS; - } + @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 16a3932..b9bebac 100644 --- a/src/main/java/me/clip/placeholderapi/events/ExpansionUnregisterEvent.java +++ b/src/main/java/me/clip/placeholderapi/events/ExpansionUnregisterEvent.java @@ -25,41 +25,33 @@ import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; -public final class ExpansionUnregisterEvent extends Event -{ +public final class ExpansionUnregisterEvent extends Event { - @NotNull - private static final HandlerList HANDLERS = new HandlerList(); + @NotNull + private static final HandlerList HANDLERS = new HandlerList(); - @NotNull - private final PlaceholderExpansion expansion; + @NotNull + private final PlaceholderExpansion expansion; - public ExpansionUnregisterEvent(@NotNull final PlaceholderExpansion expansion) - { - this.expansion = expansion; - } + public ExpansionUnregisterEvent(@NotNull final PlaceholderExpansion expansion) { + this.expansion = expansion; + } + @NotNull + public static HandlerList getHandlerList() { + return HANDLERS; + } - @NotNull - public PlaceholderExpansion getExpansion() - { - return expansion; - } + @NotNull + public PlaceholderExpansion getExpansion() { + return expansion; + } - - @NotNull - @Override - public HandlerList getHandlers() - { - return HANDLERS; - } - - - @NotNull - public static HandlerList getHandlerList() - { - return HANDLERS; - } + @NotNull + @Override + public HandlerList getHandlers() { + return HANDLERS; + } } diff --git a/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java b/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java index eb39923..0452d29 100644 --- a/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java +++ b/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java @@ -29,49 +29,42 @@ import org.jetbrains.annotations.NotNull; * @deprecated This event is no longer used. */ @Deprecated -public final class PlaceholderHookUnloadEvent extends Event -{ +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 String getHookName() - { - return plugin; - } + @NotNull + public static HandlerList getHandlerList() { + return HANDLERS; + } - @NotNull - public PlaceholderHook getHook() - { - return placeholderHook; - } + @NotNull + public String getHookName() { + return plugin; + } + @NotNull + public PlaceholderHook getHook() { + return placeholderHook; + } - @NotNull - @Override - public HandlerList getHandlers() - { - return HANDLERS; - } - - - @NotNull - public static HandlerList getHandlerList() - { - return HANDLERS; - } + @NotNull + @Override + public HandlerList getHandlers() { + return HANDLERS; + } } diff --git a/src/main/java/me/clip/placeholderapi/exceptions/NoDefaultCommandException.java b/src/main/java/me/clip/placeholderapi/exceptions/NoDefaultCommandException.java index 4a83616..8ba6a9f 100644 --- a/src/main/java/me/clip/placeholderapi/exceptions/NoDefaultCommandException.java +++ b/src/main/java/me/clip/placeholderapi/exceptions/NoDefaultCommandException.java @@ -21,8 +21,9 @@ package me.clip.placeholderapi.exceptions; public final class NoDefaultCommandException extends RuntimeException { - public NoDefaultCommandException(final String message) { - super(message); - } + + public NoDefaultCommandException(final String message) { + super(message); + } } diff --git a/src/main/java/me/clip/placeholderapi/expansion/Cacheable.java b/src/main/java/me/clip/placeholderapi/expansion/Cacheable.java index ac84431..e002c44 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Cacheable.java +++ b/src/main/java/me/clip/placeholderapi/expansion/Cacheable.java @@ -29,8 +29,8 @@ package me.clip.placeholderapi.expansion; */ public interface Cacheable { - /** - * Called when the implementing class is unregistered from PlaceholderAPI - */ - void clear(); + /** + * Called when the implementing class is unregistered from PlaceholderAPI + */ + void clear(); } diff --git a/src/main/java/me/clip/placeholderapi/expansion/Cleanable.java b/src/main/java/me/clip/placeholderapi/expansion/Cleanable.java index 7107fa8..e08f0d6 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Cleanable.java +++ b/src/main/java/me/clip/placeholderapi/expansion/Cleanable.java @@ -31,10 +31,10 @@ import org.bukkit.entity.Player; */ public interface Cleanable { - /** - * Called when a player leaves the server - * - * @param p (@link Player} who left the server - */ - void cleanup(Player p); + /** + * Called when a player leaves the server + * + * @param p (@link Player} who left the server + */ + void cleanup(Player p); } diff --git a/src/main/java/me/clip/placeholderapi/expansion/Configurable.java b/src/main/java/me/clip/placeholderapi/expansion/Configurable.java index 47b3adc..5660f64 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Configurable.java +++ b/src/main/java/me/clip/placeholderapi/expansion/Configurable.java @@ -30,14 +30,14 @@ import java.util.Map; */ public interface Configurable { - /** - * This method will be called before the implementing class is registered to obtain a map of - * configuration options that the implementing class needs These paths and values will be added to - * the PlaceholderAPI config.yml in the configuration section expansions.(placeholder - * identifier).(your key): (your value) - * - * @return Map of config path / values which need to be added / removed from the PlaceholderAPI - * config.yml file - */ - Map getDefaults(); + /** + * This method will be called before the implementing class is registered to obtain a map of + * configuration options that the implementing class needs These paths and values will be added to + * the PlaceholderAPI config.yml in the configuration section expansions.(placeholder + * identifier).(your key): (your value) + * + * @return Map of config path / values which need to be added / removed from the PlaceholderAPI + * config.yml file + */ + Map getDefaults(); } diff --git a/src/main/java/me/clip/placeholderapi/expansion/NMSVersion.java b/src/main/java/me/clip/placeholderapi/expansion/NMSVersion.java index f23f728..ac9a4af 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/NMSVersion.java +++ b/src/main/java/me/clip/placeholderapi/expansion/NMSVersion.java @@ -41,24 +41,24 @@ public enum NMSVersion { SPIGOT_1_15_R1("v1_15_R1"), SPIGOT_1_16_R1("v1_16_R1"); - private final String version; + private final String version; - NMSVersion(String version) { - this.version = version; + NMSVersion(String version) { + this.version = version; + } + + public static NMSVersion getVersion(String version) { + for (NMSVersion v : values()) { + if (v.getVersion().equalsIgnoreCase(version)) { + return v; + } } - public static NMSVersion getVersion(String version) { - for (NMSVersion v : values()) { - if (v.getVersion().equalsIgnoreCase(version)) { - return v; - } - } + return NMSVersion.UNKNOWN; + } - return NMSVersion.UNKNOWN; - } - - public String getVersion() { - return version; - } + public String getVersion() { + return version; + } } diff --git a/src/main/java/me/clip/placeholderapi/expansion/PlaceholderExpansion.java b/src/main/java/me/clip/placeholderapi/expansion/PlaceholderExpansion.java index 1fd32f6..3a0ba4b 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/PlaceholderExpansion.java +++ b/src/main/java/me/clip/placeholderapi/expansion/PlaceholderExpansion.java @@ -20,6 +20,9 @@ package me.clip.placeholderapi.expansion; +import java.util.Collections; +import java.util.List; +import java.util.Objects; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.PlaceholderHook; import org.bukkit.Bukkit; @@ -30,270 +33,240 @@ import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.List; -import java.util.Objects; +public abstract class PlaceholderExpansion extends PlaceholderHook { -public abstract class PlaceholderExpansion extends PlaceholderHook -{ + /** + * The placeholder identifier of this expansion + * + * @return placeholder identifier that is associated with this expansion + */ + @NotNull + public abstract String getIdentifier(); - /** - * The placeholder identifier of this expansion - * - * @return placeholder identifier that is associated with this expansion - */ - @NotNull - public abstract String getIdentifier(); + /** + * The author of this expansion + * + * @return name of the author for this expansion + */ + @NotNull + public abstract String getAuthor(); - /** - * The author of this expansion - * - * @return name of the author for this expansion - */ - @NotNull - public abstract String getAuthor(); + /** + * The version of this expansion + * + * @return current version of this expansion + */ + @NotNull + public abstract String getVersion(); - /** - * The version of this expansion - * - * @return current version of this expansion - */ - @NotNull - public abstract String getVersion(); - - @Nullable - @Override /* override for now >:) */ - public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params) - { - return super.onRequest(player, params); - } + @Nullable + @Override /* override for now >:) */ + public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params) { + return super.onRequest(player, params); + } - /** - * The name of this expansion - * - * @return {@link #getIdentifier()} by default, name of this expansion if specified - */ - @NotNull - public String getName() - { - return getIdentifier(); - } + /** + * The name of this expansion + * + * @return {@link #getIdentifier()} by default, name of this expansion if specified + */ + @NotNull + public String getName() { + return getIdentifier(); + } - /** - * The name of the plugin that this expansion hooks into. by default will null - * - * @return plugin name that this expansion requires to function - */ - @Nullable - public String getRequiredPlugin() - { - return getPlugin(); - } + /** + * The name of the plugin that this expansion hooks into. by default will null + * + * @return plugin name that this expansion requires to function + */ + @Nullable + public String getRequiredPlugin() { + return getPlugin(); + } - /** - * The placeholders associated with this expansion - * - * @return placeholder list that this expansion provides - */ - @NotNull - public List getPlaceholders() - { - return Collections.emptyList(); - } + /** + * The placeholders associated with this expansion + * + * @return placeholder list that this expansion provides + */ + @NotNull + public List getPlaceholders() { + return Collections.emptyList(); + } - /** - * Expansions that do not use the ecloud and instead register from the dependency should set this - * to true to ensure that your placeholder expansion is not unregistered when the papi reload - * command is used - * - * @return if this expansion should persist through placeholder reloads - */ - public boolean persist() - { - return false; - } + /** + * Expansions that do not use the ecloud and instead register from the dependency should set this + * to true to ensure that your placeholder expansion is not unregistered when the papi reload + * command is used + * + * @return if this expansion should persist through placeholder reloads + */ + public boolean persist() { + return false; + } - /** - * Check if this placeholder identifier has already been registered - * - * @return true if the identifier for this expansion is already registered - */ - public final boolean isRegistered() - { - return getPlaceholderAPI().getLocalExpansionManager().findExpansionByIdentifier(getIdentifier()).map(it -> it.equals(this)).orElse(false); - } + /** + * Check if this placeholder identifier has already been registered + * + * @return true if the identifier for this expansion is already registered + */ + public final boolean isRegistered() { + return getPlaceholderAPI().getLocalExpansionManager().findExpansionByIdentifier(getIdentifier()) + .map(it -> it.equals(this)).orElse(false); + } - /** - * If any requirements need to be checked before this expansion should register, you can check - * them here - * - * @return true if this hook meets all the requirements to register - */ - public boolean canRegister() - { - return getRequiredPlugin() == null || Bukkit.getPluginManager().getPlugin(getRequiredPlugin()) != null; - } + /** + * If any requirements need to be checked before this expansion should register, you can check + * them here + * + * @return true if this hook meets all the requirements to register + */ + public boolean canRegister() { + return getRequiredPlugin() == null + || Bukkit.getPluginManager().getPlugin(getRequiredPlugin()) != null; + } - /** - * Attempt to register this PlaceholderExpansion - * - * @return true if this expansion is now registered with PlaceholderAPI - */ - public boolean register() - { - return canRegister() && getPlaceholderAPI().getLocalExpansionManager().register(this); - } + /** + * Attempt to register this PlaceholderExpansion + * + * @return true if this expansion is now registered with PlaceholderAPI + */ + public boolean register() { + return canRegister() && getPlaceholderAPI().getLocalExpansionManager().register(this); + } - /** - * Attempt to unregister this PlaceholderExpansion - * - * @return true if this expansion is now unregistered with PlaceholderAPI - */ - public final boolean unregister() - { - return getPlaceholderAPI().getLocalExpansionManager().unregister(this); - } + /** + * Attempt to unregister this PlaceholderExpansion + * + * @return true if this expansion is now unregistered with PlaceholderAPI + */ + public final boolean unregister() { + return getPlaceholderAPI().getLocalExpansionManager().unregister(this); + } - /** - * Quick getter for the {@link PlaceholderAPIPlugin} instance - * - * @return {@link PlaceholderAPIPlugin} instance - */ - @NotNull - public final PlaceholderAPIPlugin getPlaceholderAPI() - { - return PlaceholderAPIPlugin.getInstance(); - } + /** + * Quick getter for the {@link PlaceholderAPIPlugin} instance + * + * @return {@link PlaceholderAPIPlugin} instance + */ + @NotNull + public final PlaceholderAPIPlugin getPlaceholderAPI() { + return PlaceholderAPIPlugin.getInstance(); + } + // === Configuration === - // === Configuration === + @Nullable + public final ConfigurationSection getConfigSection() { + return getPlaceholderAPI().getConfig().getConfigurationSection("expansions." + getIdentifier()); + } - @Nullable - public final ConfigurationSection getConfigSection() - { - return getPlaceholderAPI().getConfig().getConfigurationSection("expansions." + getIdentifier()); - } + @Nullable + public final ConfigurationSection getConfigSection(@NotNull final String path) { + final ConfigurationSection section = getConfigSection(); + return section == null ? null : section.getConfigurationSection(path); + } - @Nullable - public final ConfigurationSection getConfigSection(@NotNull final String path) - { - final ConfigurationSection section = getConfigSection(); - return section == null ? null : section.getConfigurationSection(path); - } + @Nullable + @Contract("_, !null -> !null") + public final Object get(@NotNull final String path, final Object def) { + final ConfigurationSection section = getConfigSection(); + return section == null ? def : section.get(path, def); + } - @Nullable - @Contract("_, !null -> !null") - public final Object get(@NotNull final String path, final Object def) - { - final ConfigurationSection section = getConfigSection(); - return section == null ? def : section.get(path, def); - } + public final int getInt(@NotNull final String path, final int def) { + final ConfigurationSection section = getConfigSection(); + return section == null ? def : section.getInt(path, def); + } - public final int getInt(@NotNull final String path, final int def) - { - final ConfigurationSection section = getConfigSection(); - return section == null ? def : section.getInt(path, def); - } + public final long getLong(@NotNull final String path, final long def) { + final ConfigurationSection section = getConfigSection(); + return section == null ? def : section.getLong(path, def); + } - public final long getLong(@NotNull final String path, final long def) - { - final ConfigurationSection section = getConfigSection(); - return section == null ? def : section.getLong(path, def); - } + public final double getDouble(@NotNull final String path, final double def) { + final ConfigurationSection section = getConfigSection(); + return section == null ? def : section.getDouble(path, def); + } - public final double getDouble(@NotNull final String path, final double def) - { - final ConfigurationSection section = getConfigSection(); - return section == null ? def : section.getDouble(path, def); - } + @Nullable + @Contract("_, !null -> !null") + public final String getString(@NotNull final String path, @Nullable final String def) { + final ConfigurationSection section = getConfigSection(); + return section == null ? def : section.getString(path, def); + } - @Nullable - @Contract("_, !null -> !null") - public final String getString(@NotNull final String path, @Nullable final String def) - { - final ConfigurationSection section = getConfigSection(); - return section == null ? def : section.getString(path, def); - } + @NotNull + public final List getStringList(@NotNull final String path) { + final ConfigurationSection section = getConfigSection(); + return section == null ? Collections.emptyList() : section.getStringList(path); + } - @NotNull - public final List getStringList(@NotNull final String path) - { - final ConfigurationSection section = getConfigSection(); - return section == null ? Collections.emptyList() : section.getStringList(path); - } + public final boolean configurationContains(@NotNull final String path) { + final ConfigurationSection section = getConfigSection(); + return section != null && section.contains(path); + } - public final boolean configurationContains(@NotNull final String path) - { - final ConfigurationSection section = getConfigSection(); - return section != null && section.contains(path); - } + @Override + public final boolean equals(final Object o) { + if (this == o) { + return true; + } + if (!(o instanceof PlaceholderExpansion)) { + return false; + } - @Override - public final boolean equals(final Object o) - { - if (this == o) - { - return true; - } - if (!(o instanceof PlaceholderExpansion)) - { - return false; - } + final PlaceholderExpansion expansion = (PlaceholderExpansion) o; - final PlaceholderExpansion expansion = (PlaceholderExpansion) o; + return getIdentifier().equals(expansion.getIdentifier()) && + getAuthor().equals(expansion.getAuthor()) && + getVersion().equals(expansion.getVersion()); + } - return getIdentifier().equals(expansion.getIdentifier()) && - getAuthor().equals(expansion.getAuthor()) && - getVersion().equals(expansion.getVersion()); - } + @Override + public final int hashCode() { + return Objects.hash(getIdentifier(), getAuthor(), getVersion()); + } - @Override - public final int hashCode() - { - return Objects.hash(getIdentifier(), getAuthor(), getVersion()); - } + @Override + public final String toString() { + return String.format("PlaceholderExpansion[name: '%s', author: '%s', version: '%s']", getName(), + getAuthor(), getVersion()); + } - @Override - public final String toString() - { - return String.format("PlaceholderExpansion[name: '%s', author: '%s', version: '%s']", getName(), getAuthor(), getVersion()); - } + // === Deprecated API === - // === Deprecated API === + /** + * @deprecated As of versions greater than 2.8.7, use {@link #getRequiredPlugin()} + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.11.0") + public String getPlugin() { + return null; + } - /** - * @deprecated As of versions greater than 2.8.7, use {@link #getRequiredPlugin()} - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.11.0") - public String getPlugin() - { - return null; - } + /** + * @deprecated As of versions greater than 2.8.7, use the expansion cloud to show a description + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.11.0") + public String getDescription() { + return null; + } - /** - * @deprecated As of versions greater than 2.8.7, use the expansion cloud to show a description - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.11.0") - public String getDescription() - { - return null; - } - - /** - * @deprecated As of versions greater than 2.8.7, use the expansion cloud to display a link - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.11.0") - public String getLink() - { - return null; - } + /** + * @deprecated As of versions greater than 2.8.7, use the expansion cloud to display a link + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.11.0") + public String getLink() { + return null; + } } diff --git a/src/main/java/me/clip/placeholderapi/expansion/Relational.java b/src/main/java/me/clip/placeholderapi/expansion/Relational.java index e30943f..ca80f6e 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Relational.java +++ b/src/main/java/me/clip/placeholderapi/expansion/Relational.java @@ -24,5 +24,5 @@ import org.bukkit.entity.Player; public interface Relational { - String onPlaceholderRequest(Player one, Player two, String identifier); + String onPlaceholderRequest(Player one, Player two, String identifier); } diff --git a/src/main/java/me/clip/placeholderapi/expansion/Taskable.java b/src/main/java/me/clip/placeholderapi/expansion/Taskable.java index 2d77140..f32a6a9 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Taskable.java +++ b/src/main/java/me/clip/placeholderapi/expansion/Taskable.java @@ -23,15 +23,15 @@ package me.clip.placeholderapi.expansion; public interface Taskable { - /** - * Called when the implementing class has successfully been registered to the placeholder map - * Tasks that need to be performed when this expansion is registered should go here - */ - void start(); + /** + * Called when the implementing class has successfully been registered to the placeholder map + * Tasks that need to be performed when this expansion is registered should go here + */ + void start(); - /** - * Called when the implementing class has been unregistered from PlaceholderAPI Tasks that need to - * be performed when this expansion has unregistered should go here - */ - void stop(); + /** + * Called when the implementing class has been unregistered from PlaceholderAPI Tasks that need to + * be performed when this expansion has unregistered should go here + */ + void stop(); } diff --git a/src/main/java/me/clip/placeholderapi/expansion/Version.java b/src/main/java/me/clip/placeholderapi/expansion/Version.java index 27ffd7b..e789243 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Version.java +++ b/src/main/java/me/clip/placeholderapi/expansion/Version.java @@ -22,24 +22,24 @@ package me.clip.placeholderapi.expansion; 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/VersionSpecific.java b/src/main/java/me/clip/placeholderapi/expansion/VersionSpecific.java index 68a1c03..b539532 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/VersionSpecific.java +++ b/src/main/java/me/clip/placeholderapi/expansion/VersionSpecific.java @@ -30,11 +30,11 @@ package me.clip.placeholderapi.expansion; */ public interface VersionSpecific { - /** - * This method is called before the expansion is attempted to be registered The server version - * will be passed to this method so you know what version the server is currently running. - * - * @return true if your expansion is compatible with the version the server is running. - */ - boolean isCompatibleWith(Version v); + /** + * This method is called before the expansion is attempted to be registered The server version + * will be passed to this method so you know what version the server is currently running. + * + * @return true if your expansion is compatible with the version the server is running. + */ + boolean isCompatibleWith(Version v); } 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 7e39a75..b6516b9 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/cloud/CloudExpansion.java +++ b/src/main/java/me/clip/placeholderapi/expansion/cloud/CloudExpansion.java @@ -20,183 +20,183 @@ package me.clip.placeholderapi.expansion.cloud; -import me.clip.placeholderapi.util.TimeUtil; - 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 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 class Version { + + private String url, version, release_notes; + + public String getUrl() { + return url; } - public String getTimeSinceLastUpdate() { - int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - getLastUpdate()); - return TimeUtil.getTime(time); + public void setUrl(String url) { + this.url = url; } - public String getName() { - return name; + public String getVersion() { + return version; } - public void setName(String name) { - this.name = name; + public void setVersion(String version) { + this.version = version; } - public String getAuthor() { - return author; + public String getReleaseNotes() { + return 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 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; - } + 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 9c1a7a1..6e77bbb 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/manager/CloudExpansionManager.java +++ b/src/main/java/me/clip/placeholderapi/expansion/manager/CloudExpansionManager.java @@ -24,12 +24,6 @@ import com.google.common.collect.ImmutableMap; import com.google.common.io.Resources; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.expansion.cloud.CloudExpansion; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -38,7 +32,11 @@ import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ConcurrentHashMap; @@ -46,243 +44,216 @@ 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; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; -public final class CloudExpansionManager -{ +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<>(); - public CloudExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) - { - this.plugin = plugin; - } + public CloudExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) { + this.plugin = plugin; + } + @NotNull + private static String toIndexName(@NotNull final String name) { + return name.toLowerCase().replace(' ', '_'); + } - public void load() - { - clean(); - fetch(plugin.getPlaceholderAPIConfig().cloudAllowUnverifiedExpansions()); - } + @NotNull + private static String toIndexName(@NotNull final CloudExpansion expansion) { + return toIndexName(expansion.getName()); + } - public void kill() - { - clean(); - } + public void load() { + clean(); + fetch(plugin.getPlaceholderAPIConfig().cloudAllowUnverifiedExpansions()); + } + public void kill() { + clean(); + } - @NotNull - @Unmodifiable - public Map getCloudExpansions() - { - return ImmutableMap.copyOf(cache); - } + @NotNull + @Unmodifiable + public Map getCloudExpansions() { + return ImmutableMap.copyOf(cache); + } - @NotNull - @Unmodifiable - public Map getCloudExpansionsInstalled() - { - if (cache.isEmpty()) - { - return Collections.emptyMap(); - } + @NotNull + @Unmodifiable + public Map getCloudExpansionsInstalled() { + if (cache.isEmpty()) { + return Collections.emptyMap(); + } - return cache.values() - .stream() - .filter(CloudExpansion::hasExpansion) - .collect(INDEXED_NAME_COLLECTOR); - } + 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 + @Unmodifiable + public Map getCloudExpansionsByAuthor(@NotNull final String author) { + if (cache.isEmpty()) { + return Collections.emptyMap(); + } - return cache.values() - .stream() - .filter(expansion -> author.equalsIgnoreCase(expansion.getAuthor())) - .collect(INDEXED_NAME_COLLECTOR); - } + return cache.values() + .stream() + .filter(expansion -> author.equalsIgnoreCase(expansion.getAuthor())) + .collect(INDEXED_NAME_COLLECTOR); + } - @NotNull - @Unmodifiable - public Set getCloudExpansionAuthors() - { - return cache.values().stream().map(CloudExpansion::getAuthor).collect(Collectors.toSet()); - } + @NotNull + @Unmodifiable + public Set getCloudExpansionAuthors() { + return cache.values().stream().map(CloudExpansion::getAuthor).collect(Collectors.toSet()); + } + public int getCloudExpansionAuthorCount() { + return getCloudExpansionAuthors().size(); + } - public int getCloudExpansionAuthorCount() - { - return getCloudExpansionAuthors().size(); - } + public int getCloudUpdateCount() { + return ((int) plugin.getLocalExpansionManager() + .getExpansions() + .stream() + .filter(expansion -> findCloudExpansionByName(expansion.getName()) + .map(CloudExpansion::shouldUpdate).orElse(false)) + .count()); + } - public int getCloudUpdateCount() - { - return ((int) plugin.getLocalExpansionManager() - .getExpansions() - .stream() - .filter(expansion -> findCloudExpansionByName(expansion.getName()).map(CloudExpansion::shouldUpdate).orElse(false)) - .count()); - } + @NotNull + public Optional findCloudExpansionByName(@NotNull final String name) { + return Optional.ofNullable(cache.get(toIndexName(name))); + } + public void clean() { + cache.clear(); - @NotNull - public Optional findCloudExpansionByName(@NotNull final String name) - { - return Optional.ofNullable(cache.get(toIndexName(name))); - } + await.values().forEach(future -> future.cancel(true)); + await.clear(); + } + public void fetch(final boolean allowUnverified) { + plugin.getLogger().info("Fetching available expansion information..."); - public void clean() - { - cache.clear(); + CompletableFuture> future = CompletableFuture.supplyAsync(() -> { + final Map values = new HashMap<>(); - await.values().forEach(future -> future.cancel(true)); - await.clear(); - } + try { + //noinspection UnstableApiUsage + final String json = Resources.toString(new URL(API_URL), StandardCharsets.UTF_8); + values.putAll(GSON.fromJson(json, TYPE)); + } catch (final IOException ex) { + throw new CompletionException(ex); + } - public void fetch(final boolean allowUnverified) - { - plugin.getLogger().info("Fetching available expansion information..."); + values.values().removeIf(value -> value.getLatestVersion() == null + || value.getVersion(value.getLatestVersion()) == null); - CompletableFuture> future = CompletableFuture.supplyAsync(() -> { - final Map values = new HashMap<>(); + return values; + }); - try - { - //noinspection UnstableApiUsage - final String json = Resources.toString(new URL(API_URL), StandardCharsets.UTF_8); - values.putAll(GSON.fromJson(json, TYPE)); - } - catch (final IOException ex) - { - throw new CompletionException(ex); - } + if (!allowUnverified) { + future = future.thenApplyAsync((values) -> { + values.values().removeIf(expansion -> !expansion.isVerified()); + return values; + }); + } - values.values().removeIf(value -> value.getLatestVersion() == null || value.getVersion(value.getLatestVersion()) == null); + future = future.thenApplyAsync((values) -> { - return values; - }); + values.forEach((name, expansion) -> { + expansion.setName(name); + final Optional local = plugin.getLocalExpansionManager() + .findExpansionByName(name); + if (local.isPresent() && local.get().isRegistered()) { + expansion.setHasExpansion(true); + expansion.setShouldUpdate(!local.get().getVersion().equals(expansion.getLatestVersion())); + } + }); - if (!allowUnverified) - { - future = future.thenApplyAsync((values) -> { - values.values().removeIf(expansion -> !expansion.isVerified()); - return values; - }); - } + return values; + }); + future.whenComplete((expansions, exception) -> { - future = future.thenApplyAsync((values) -> { + if (exception != null) { + plugin.getLogger() + .log(Level.WARNING, "failed to download expansion information", exception); + return; + } - values.forEach((name, expansion) -> { - expansion.setName(name); + for (final CloudExpansion expansion : expansions.values()) { + this.cache.put(toIndexName(expansion), expansion); + } + }); + } - final Optional local = plugin.getLocalExpansionManager().findExpansionByName(name); - if (local.isPresent() && local.get().isRegistered()) - { - expansion.setHasExpansion(true); - expansion.setShouldUpdate(!local.get().getVersion().equals(expansion.getLatestVersion())); - } - }); + public boolean isDownloading(@NotNull final CloudExpansion expansion) { + return await.containsKey(toIndexName(expansion)); + } - return values; - }); + @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; + } - future.whenComplete((expansions, exception) -> { + final File file = new File(plugin.getLocalExpansionManager().getExpansionsFolder(), + "Expansion-" + toIndexName(expansion) + ".jar"); - if (exception != null) - { - plugin.getLogger().log(Level.WARNING, "failed to download expansion information", exception); - return; - } + 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; + }); - for (final CloudExpansion expansion : expansions.values()) - { - this.cache.put(toIndexName(expansion), expansion); - } - }); - } + download.whenCompleteAsync((value, exception) -> { + await.remove(toIndexName(expansion)); + if (exception != null) { + plugin.getLogger().log(Level.SEVERE, + "failed to download " + expansion.getName() + ":" + version.getVersion(), exception); + } + }); - public boolean isDownloading(@NotNull final CloudExpansion expansion) - { - return await.containsKey(toIndexName(expansion)); - } + await.put(toIndexName(expansion), download); - - @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; - } - - final File file = new File(plugin.getLocalExpansionManager().getExpansionsFolder(), "Expansion-" + toIndexName(expansion) + ".jar"); - - 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; - }); - - download.whenCompleteAsync((value, exception) -> { - await.remove(toIndexName(expansion)); - - if (exception != null) - { - plugin.getLogger().log(Level.SEVERE, "failed to download " + expansion.getName() + ":" + version.getVersion(), exception); - } - }); - - await.put(toIndexName(expansion), download); - - return download; - } - - - @NotNull - private static String toIndexName(@NotNull final String name) - { - return name.toLowerCase().replace(' ', '_'); - } - - @NotNull - private static String toIndexName(@NotNull final CloudExpansion expansion) - { - return toIndexName(expansion.getName()); - } + 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 cec3c90..c6c4eae 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/manager/LocalExpansionManager.java +++ b/src/main/java/me/clip/placeholderapi/expansion/manager/LocalExpansionManager.java @@ -22,10 +22,25 @@ package me.clip.placeholderapi.expansion.manager; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; +import java.io.File; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.logging.Level; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.events.ExpansionRegisterEvent; import me.clip.placeholderapi.events.ExpansionUnregisterEvent; -import me.clip.placeholderapi.expansion.*; +import me.clip.placeholderapi.expansion.Cacheable; +import me.clip.placeholderapi.expansion.Cleanable; +import me.clip.placeholderapi.expansion.Configurable; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.Taskable; +import me.clip.placeholderapi.expansion.VersionSpecific; import me.clip.placeholderapi.expansion.cloud.CloudExpansion; import me.clip.placeholderapi.util.FileUtil; import me.clip.placeholderapi.util.Futures; @@ -44,381 +59,318 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Unmodifiable; -import java.io.File; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import java.util.logging.Level; - -public final class LocalExpansionManager implements Listener -{ - - @NotNull - private static final String EXPANSIONS_FOLDER_NAME = "expansions"; - - - @NotNull - private final File folder; - @NotNull - private final PlaceholderAPIPlugin plugin; - - @NotNull - private final Map expansions = new HashMap<>(); - - - public LocalExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) - { - this.plugin = plugin; - this.folder = new File(plugin.getDataFolder(), EXPANSIONS_FOLDER_NAME); - - if (!this.folder.exists() && !folder.mkdirs()) - { - plugin.getLogger().log(Level.WARNING, "failed to create expansions folder!"); - } - } - - public void load(@NotNull final CommandSender sender) - { - registerAll(sender); - } - - public void kill() - { - unregisterAll(); - } - - - @NotNull - public File getExpansionsFolder() - { - return folder; - } - - public int getExpansionsCount() - { - return expansions.size(); - } - - - @NotNull - @Unmodifiable - public Collection getIdentifiers() - { - return ImmutableSet.copyOf(expansions.keySet()); - } - - @NotNull - @Unmodifiable - public Collection getExpansions() - { - return ImmutableSet.copyOf(expansions.values()); - } - - - @Nullable - public PlaceholderExpansion getExpansion(@NotNull final String identifier) - { - return expansions.get(identifier.toLowerCase()); - } - - - @NotNull - public Optional findExpansionByName(@NotNull final String name) - { - return expansions.values().stream().filter(expansion -> name.equalsIgnoreCase(expansion.getName())).findFirst(); - } - - @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 || !expansion.register()) - { - return Optional.empty(); - } - - return Optional.of(expansion); - } - catch (final LinkageError ex) - { - plugin.getLogger().severe("expansion class " + clazz.getSimpleName() + " is outdated: \n" + - "Failed to load due to a [" + ex.getClass().getSimpleName() + "], attempted to use " + ex.getMessage()); - } - - return Optional.empty(); - } - - /** - * Do not call this method yourself, use {@link PlaceholderExpansion#register()} - */ - @ApiStatus.Internal - public boolean register(@NotNull final PlaceholderExpansion expansion) - { - final String identifier = expansion.getIdentifier().toLowerCase(); - - 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); - } - } - else - { - if (!cfg.contains(pre + entries.getKey())) - { - save = true; - cfg.set(pre + entries.getKey(), entries.getValue()); - } - } - } - } - - if (save) - { - plugin.saveConfig(); - plugin.reloadConfig(); - } - } - - if (expansion instanceof VersionSpecific) - { - VersionSpecific nms = (VersionSpecific) expansion; - if (!nms.isCompatibleWith(PlaceholderAPIPlugin.getServerVersion())) - { - plugin.getLogger().info("Your server version is not compatible with expansion: " + expansion.getIdentifier() + " version: " + expansion.getVersion()); - return false; - } - } - - final PlaceholderExpansion removed = expansions.get(identifier); - if (removed != null && !removed.unregister()) - { - return false; - } - - final ExpansionRegisterEvent event = new ExpansionRegisterEvent(expansion); - Bukkit.getPluginManager().callEvent(event); - - if (event.isCancelled()) - { - return false; - } - - expansions.put(identifier, expansion); - - if (expansion instanceof Listener) - { - Bukkit.getPluginManager().registerEvents(((Listener) expansion), plugin); - } - - plugin.getLogger().info("Successfully registered expansion: " + expansion.getIdentifier()); - - if (expansion instanceof Taskable) - { - ((Taskable) expansion).start(); - } - - if (plugin.getPlaceholderAPIConfig().isCloudEnabled()) - { - final Optional cloudExpansion = plugin.getCloudExpansionManager().findCloudExpansionByName(identifier); - if (cloudExpansion.isPresent()) - { - cloudExpansion.get().setHasExpansion(true); - cloudExpansion.get().setShouldUpdate(!cloudExpansion.get().getLatestVersion().equals(expansion.getVersion())); - } - } - - return true; - } - - /** - * Do not call this method yourself, use {@link PlaceholderExpansion#unregister()} - */ - @ApiStatus.Internal - public boolean unregister(@NotNull final PlaceholderExpansion expansion) - { - if (expansions.remove(expansion.getIdentifier()) == 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) - { - plugin.getLogger().info("Placeholder expansion registration initializing..."); - - Futures.onMainThread(plugin, findExpansionsOnDisk(), (classes, exception) -> { - if (exception != null) - { - plugin.getLogger().log(Level.SEVERE, "failed to load class files of expansions", exception); - return; - } - - final long registered = classes.stream().map(this::register).filter(Optional::isPresent).count(); - - Msg.msg(sender, - registered == 0 ? "&6No expansions were registered!" : registered + "&a placeholder hooks successfully registered!"); - }); - } - - private void unregisterAll() - { - for (final PlaceholderExpansion expansion : Sets.newHashSet(expansions.values())) - { - if (expansion.persist()) - { - continue; - } - - expansion.unregister(); - } - } - - - @NotNull - public CompletableFuture<@NotNull List<@NotNull Class>> findExpansionsOnDisk() - { - return Arrays.stream(folder.listFiles((dir, name) -> name.endsWith(".jar"))) - .map(this::findExpansionInFile) - .collect(Futures.collector()); - } - - @NotNull - public CompletableFuture<@Nullable Class> findExpansionInFile(@NotNull final File file) - { - return CompletableFuture.supplyAsync(() -> { - try - { - return FileUtil.findClass(file, PlaceholderExpansion.class); - } - catch (final VerifyError ex) - { - plugin.getLogger().severe("expansion file " + file.getName() + " is outdated: \n" + - "Failed to load due to a [" + ex.getClass().getSimpleName() + "], attempted to use" + ex.getMessage().substring(ex.getMessage().lastIndexOf(' '))); - return null; - } - catch (final Exception ex) - { - throw new CompletionException(ex); - } - }); - } - - - @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()); - } - - plugin.getLogger().log(Level.SEVERE, "Failed to load placeholder expansion from class: " + clazz.getName(), ex); - 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(); - plugin.getLogger().info("Unregistered placeholder expansion: " + expansion.getName()); - } - } +public final class LocalExpansionManager implements Listener { + + @NotNull + private static final String EXPANSIONS_FOLDER_NAME = "expansions"; + + + @NotNull + private final File folder; + @NotNull + private final PlaceholderAPIPlugin plugin; + + @NotNull + private final Map expansions = new HashMap<>(); + + + public LocalExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) { + this.plugin = plugin; + this.folder = new File(plugin.getDataFolder(), EXPANSIONS_FOLDER_NAME); + + if (!this.folder.exists() && !folder.mkdirs()) { + plugin.getLogger().log(Level.WARNING, "failed to create expansions folder!"); + } + } + + public void load(@NotNull final CommandSender sender) { + registerAll(sender); + } + + public void kill() { + unregisterAll(); + } + + + @NotNull + public File getExpansionsFolder() { + return folder; + } + + public int getExpansionsCount() { + return expansions.size(); + } + + + @NotNull + @Unmodifiable + public Collection getIdentifiers() { + return ImmutableSet.copyOf(expansions.keySet()); + } + + @NotNull + @Unmodifiable + public Collection getExpansions() { + return ImmutableSet.copyOf(expansions.values()); + } + + + @Nullable + public PlaceholderExpansion getExpansion(@NotNull final String identifier) { + return expansions.get(identifier.toLowerCase()); + } + + + @NotNull + public Optional findExpansionByName(@NotNull final String name) { + return expansions.values().stream() + .filter(expansion -> name.equalsIgnoreCase(expansion.getName())).findFirst(); + } + + @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 || !expansion.register()) { + return Optional.empty(); + } + + return Optional.of(expansion); + } catch (final LinkageError ex) { + plugin.getLogger().severe("expansion class " + clazz.getSimpleName() + " is outdated: \n" + + "Failed to load due to a [" + ex.getClass().getSimpleName() + "], attempted to use " + ex + .getMessage()); + } + + return Optional.empty(); + } + + /** + * Do not call this method yourself, use {@link PlaceholderExpansion#register()} + */ + @ApiStatus.Internal + public boolean register(@NotNull final PlaceholderExpansion expansion) { + final String identifier = expansion.getIdentifier().toLowerCase(); + + 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); + } + } else { + if (!cfg.contains(pre + entries.getKey())) { + save = true; + cfg.set(pre + entries.getKey(), entries.getValue()); + } + } + } + } + + if (save) { + plugin.saveConfig(); + plugin.reloadConfig(); + } + } + + if (expansion instanceof VersionSpecific) { + VersionSpecific nms = (VersionSpecific) expansion; + if (!nms.isCompatibleWith(PlaceholderAPIPlugin.getServerVersion())) { + plugin.getLogger().info( + "Your server version is not compatible with expansion: " + expansion.getIdentifier() + + " version: " + expansion.getVersion()); + return false; + } + } + + final PlaceholderExpansion removed = expansions.get(identifier); + if (removed != null && !removed.unregister()) { + return false; + } + + final ExpansionRegisterEvent event = new ExpansionRegisterEvent(expansion); + Bukkit.getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return false; + } + + expansions.put(identifier, expansion); + + if (expansion instanceof Listener) { + Bukkit.getPluginManager().registerEvents(((Listener) expansion), plugin); + } + + plugin.getLogger().info("Successfully registered expansion: " + expansion.getIdentifier()); + + if (expansion instanceof Taskable) { + ((Taskable) expansion).start(); + } + + if (plugin.getPlaceholderAPIConfig().isCloudEnabled()) { + final Optional cloudExpansion = plugin.getCloudExpansionManager() + .findCloudExpansionByName(identifier); + if (cloudExpansion.isPresent()) { + cloudExpansion.get().setHasExpansion(true); + cloudExpansion.get().setShouldUpdate( + !cloudExpansion.get().getLatestVersion().equals(expansion.getVersion())); + } + } + + return true; + } + + /** + * Do not call this method yourself, use {@link PlaceholderExpansion#unregister()} + */ + @ApiStatus.Internal + public boolean unregister(@NotNull final PlaceholderExpansion expansion) { + if (expansions.remove(expansion.getIdentifier()) == 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) { + plugin.getLogger().info("Placeholder expansion registration initializing..."); + + Futures.onMainThread(plugin, findExpansionsOnDisk(), (classes, exception) -> { + if (exception != null) { + plugin.getLogger().log(Level.SEVERE, "failed to load class files of expansions", exception); + return; + } + + final long registered = classes.stream().map(this::register).filter(Optional::isPresent) + .count(); + + Msg.msg(sender, + registered == 0 ? "&6No expansions were registered!" + : registered + "&a placeholder hooks successfully registered!"); + }); + } + + private void unregisterAll() { + for (final PlaceholderExpansion expansion : Sets.newHashSet(expansions.values())) { + if (expansion.persist()) { + continue; + } + + expansion.unregister(); + } + } + + + @NotNull + public CompletableFuture<@NotNull List<@NotNull Class>> findExpansionsOnDisk() { + return Arrays.stream(folder.listFiles((dir, name) -> name.endsWith(".jar"))) + .map(this::findExpansionInFile) + .collect(Futures.collector()); + } + + @NotNull + public CompletableFuture<@Nullable Class> findExpansionInFile( + @NotNull final File file) { + return CompletableFuture.supplyAsync(() -> { + try { + return FileUtil.findClass(file, PlaceholderExpansion.class); + } catch (final VerifyError ex) { + plugin.getLogger().severe("expansion file " + file.getName() + " is outdated: \n" + + "Failed to load due to a [" + ex.getClass().getSimpleName() + "], attempted to use" + ex + .getMessage().substring(ex.getMessage().lastIndexOf(' '))); + return null; + } catch (final Exception ex) { + throw new CompletionException(ex); + } + }); + } + + + @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()); + } + + plugin.getLogger() + .log(Level.SEVERE, "Failed to load placeholder expansion from class: " + clazz.getName(), + ex); + 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(); + plugin.getLogger().info("Unregistered placeholder expansion: " + expansion.getName()); + } + } } diff --git a/src/main/java/me/clip/placeholderapi/libs/JSONMessage.java b/src/main/java/me/clip/placeholderapi/libs/JSONMessage.java index 680c889..b07a31c 100644 --- a/src/main/java/me/clip/placeholderapi/libs/JSONMessage.java +++ b/src/main/java/me/clip/placeholderapi/libs/JSONMessage.java @@ -17,11 +17,6 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.reflect.Constructor; @@ -32,15 +27,19 @@ import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.Vector; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; /** - * This is a complete JSON message builder class. To create a new JSONMessage do - * {@link #create(String)} + * This is a complete JSON message builder class. To create a new JSONMessage do {@link + * #create(String)} * * @author Rayzr */ @SuppressWarnings({"WeakerAccess", "unused"}) public class JSONMessage { + private static final BiMap stylesToNames; static { @@ -107,7 +106,8 @@ public class JSONMessage { * @param players The players you want to send it to */ public static void actionbar(String message, Player... players) { - ReflectionHelper.sendPacket(ReflectionHelper.createActionbarPacket(ChatColor.translateAlternateColorCodes('&', message)), players); + ReflectionHelper.sendPacket(ReflectionHelper + .createActionbarPacket(ChatColor.translateAlternateColorCodes('&', message)), players); } /** @@ -143,8 +143,8 @@ public class JSONMessage { } /** - * Converts this {@link JSONMessage} object to a String representation of the JSON. - * This is an alias of {@code toJSON().toString()}. + * Converts this {@link JSONMessage} object to a String representation of the JSON. This is an + * alias of {@code toJSON().toString()}. */ @Override public String toString() { @@ -152,8 +152,8 @@ public class JSONMessage { } /** - * Converts this {@link JSONMessage} object to the legacy formatting system, which - * uses formatting codes (like &6, &l, &4, etc.) + * Converts this {@link JSONMessage} object to the legacy formatting system, which uses formatting + * codes (like &6, &l, &4, etc.) * * @return This {@link JSONMessage} instance {@link JSONMessage} in legacy format */ @@ -184,18 +184,20 @@ public class JSONMessage { /** * Sends this as a title to all the players specified * - * @param fadeIn How many ticks to fade in - * @param stay How many ticks to stay + * @param fadeIn How many ticks to fade in + * @param stay How many ticks to stay * @param fadeOut How many ticks to fade out * @param players The players to send this to */ public void title(int fadeIn, int stay, int fadeOut, Player... players) { - ReflectionHelper.sendPacket(ReflectionHelper.createTitleTimesPacket(fadeIn, stay, fadeOut), players); + ReflectionHelper + .sendPacket(ReflectionHelper.createTitleTimesPacket(fadeIn, stay, fadeOut), players); ReflectionHelper.sendPacket(ReflectionHelper.createTitlePacket(toString()), players); } /** - * Sends this as a subtitle to all the players specified. Must be used after sending a {@link #title(int, int, int, Player...) title}. + * Sends this as a subtitle to all the players specified. Must be used after sending a {@link + * #title(int, int, int, Player...) title}. * * @param players The players to send this to */ @@ -219,8 +221,9 @@ public class JSONMessage { * @return This {@link JSONMessage} instance */ public JSONMessage color(ChatColor color) { - if (!color.isColor()) + if (!color.isColor()) { throw new IllegalArgumentException(color.name() + " is not a color."); + } last().setColor(color); return this; @@ -228,7 +231,8 @@ public class JSONMessage { /** * Sets the color of the current message part. - *
If the provided color is a hex color ({@code #rrggbb}) but the major version of MC is older than 1.16 will this + *
If the provided color is a hex color ({@code #rrggbb}) but the major version of MC is older + * than 1.16 will this * default to the color WHITE. * * @param color The color to set @@ -240,16 +244,18 @@ public class JSONMessage { /** * Sets the color of the current message part. - *
If the provided color is a hex color ({@code #rrggbb}) but the major version of MC is older than 1.16 will the provided + *
If the provided color is a hex color ({@code #rrggbb}) but the major version of MC is older + * than 1.16 will the provided * default ChatColor be used instead. * * @param color The color to set - * @param def The default ChatColor to use, when MC version is older than 1.16 + * @param def The default ChatColor to use, when MC version is older than 1.16 * @return This {@link JSONMessage} instance */ public JSONMessage color(String color, ChatColor def) { - if (color.startsWith("#") && ReflectionHelper.MAJOR_VER < 16) + if (color.startsWith("#") && ReflectionHelper.MAJOR_VER < 16) { return color(def); + } last().setColor(color); return this; @@ -263,8 +269,9 @@ public class JSONMessage { * @return This {@link JSONMessage} instance */ public JSONMessage font(String font) { - if (ReflectionHelper.MAJOR_VER < 16) + if (ReflectionHelper.MAJOR_VER < 16) { return this; + } last().setFont(font); return this; @@ -316,7 +323,8 @@ public class JSONMessage { /** * Copies the provided text to the Clipboard of the player. - *
When this is used on versions older than 1.15 will this default to {@link #suggestCommand(String) suggestCommand(String)}. + *
When this is used on versions older than 1.15 will this default to {@link + * #suggestCommand(String) suggestCommand(String)}. * * @param text The text to copy * @return This {@link JSONMessage} instance @@ -327,8 +335,8 @@ public class JSONMessage { } /** - * Changes the page of a book. Using this in a non-book context is useless - * and will probably error. + * Changes the page of a book. Using this in a non-book context is useless and will probably + * error. * * @param page The page to change to * @return This {@link JSONMessage} instance @@ -399,12 +407,13 @@ public class JSONMessage { * @return This {@link JSONMessage} instance */ public JSONMessage bar(int length) { - return then(Strings.repeat("-", length)).color(ChatColor.DARK_GRAY).style(ChatColor.STRIKETHROUGH); + return then(Strings.repeat("-", length)).color(ChatColor.DARK_GRAY) + .style(ChatColor.STRIKETHROUGH); } /** - * Adds a horizontal bar to the message that's 53 characters long. This is - * the default width of the player's chat window. + * Adds a horizontal bar to the message that's 53 characters long. This is the default width of + * the player's chat window. * * @return This {@link JSONMessage} instance */ @@ -451,7 +460,8 @@ public class JSONMessage { if (current >= parts.size() || totalLineLength + rawLength >= 53) { int padding = Math.max(0, (53 - totalLineLength) / 2); - currentLine.firstElement().setText(Strings.repeat(" ", padding) + currentLine.firstElement().getText()); + currentLine.firstElement() + .setText(Strings.repeat(" ", padding) + currentLine.firstElement().getText()); currentLine.lastElement().setText(currentLine.lastElement().getText() + "\n"); currentLine.clear(); break; @@ -502,7 +512,8 @@ public class JSONMessage { * MC 1.16 changed "value" to "contents", but only for Hover events... Don't ask why. * Since this lib only has tooltip and achievement can we simply check if action starts with "show_" */ - String valueType = (ReflectionHelper.MAJOR_VER >= 16 && action.startsWith("show_")) ? "contents" : "value"; + String valueType = + (ReflectionHelper.MAJOR_VER >= 16 && action.startsWith("show_")) ? "contents" : "value"; if (value instanceof JsonElement) { obj.add(valueType, (JsonElement) value); @@ -586,14 +597,16 @@ public class JSONMessage { /** * Copies the provided text to the clipboard of the player. - *
When used on versions older than 1.15 will this {@link #suggestCommand(String) suggest the text} instead. + *
When used on versions older than 1.15 will this {@link #suggestCommand(String) suggest + * the text} instead. * * @param text The text to copy. * @return The {@link MessageEvent} */ public static MessageEvent copyText(String text) { - if (ReflectionHelper.MAJOR_VER < 15) + if (ReflectionHelper.MAJOR_VER < 15) { return suggestCommand(text); + } return new MessageEvent("copy_to_clipboard", text); } @@ -682,7 +695,8 @@ public class JSONMessage { if (MAJOR_VER < 8) { stringToChat = getClass("{nms}.ChatSerializer").getMethod("a", String.class); } else { - stringToChat = getClass("{nms}.IChatBaseComponent$ChatSerializer").getMethod("a", String.class); + stringToChat = getClass("{nms}.IChatBaseComponent$ChatSerializer") + .getMethod("a", String.class); } GET_HANDLE = MethodHandles.lookup().unreflect(getHandle); @@ -698,7 +712,8 @@ public class JSONMessage { Class titleAction = getClass("{nms}.PacketPlayOutTitle$EnumTitleAction"); titlePacketConstructor = packetPlayOutTitle.getConstructor(titleAction, iChatBaseComponent); - titleTimesPacketConstructor = packetPlayOutTitle.getConstructor(int.class, int.class, int.class); + titleTimesPacketConstructor = packetPlayOutTitle + .getConstructor(int.class, int.class, int.class); enumActionTitle = titleAction.getField("TITLE").get(null); enumActionSubtitle = titleAction.getField("SUBTITLE").get(null); @@ -833,7 +848,8 @@ public class JSONMessage { * Attempts to convert a String representing a JSON message into a usable object * * @param json The JSON to attempt to parse - * @return The object representing the text in JSON form, or null if something went wrong converting the String to JSON data + * @return The object representing the text in JSON form, or null if something went + * wrong converting the String to JSON data */ static Object fromJson(String json) { assertIsSetup(); @@ -857,7 +873,8 @@ public class JSONMessage { } private static Class getClass(String path) throws ClassNotFoundException { - return Class.forName(path.replace("{nms}", "net.minecraft.server." + version).replace("{obc}", "org.bukkit.craftbukkit." + version)); + return Class.forName(path.replace("{nms}", "net.minecraft.server." + version) + .replace("{obc}", "org.bukkit.craftbukkit." + version)); } private static void setFieldValue(Field field, Object instance, Object value) { @@ -890,7 +907,8 @@ public class JSONMessage { } /** - * Defines a section of the message, and represents the format that all JSON messages must follow in Minecraft. + * Defines a section of the message, and represents the format that all JSON messages must follow + * in Minecraft. *
*
* Reference @@ -1009,8 +1027,10 @@ public class JSONMessage { return legacyColor; } - if (this.color.startsWith("#") && ReflectionHelper.MAJOR_VER < 16) - throw new IllegalStateException("Custom Hex colors can only be used in Minecraft 1.16 or newer!"); + if (this.color.startsWith("#") && ReflectionHelper.MAJOR_VER < 16) { + throw new IllegalStateException( + "Custom Hex colors can only be used in Minecraft 1.16 or newer!"); + } try { return ChatColor.valueOf(this.color.toUpperCase()); @@ -1029,15 +1049,6 @@ public class JSONMessage { setLegacyColor(color); } - /** - * @param color The legacy ChatColor to set - * @deprecated Use {@link #setColor(String)} instead - */ - @Deprecated - public void setLegacyColor(ChatColor color) { - legacyColor = color; - } - /** * @param color The color to set */ @@ -1048,6 +1059,15 @@ public class JSONMessage { this.color = color; } + /** + * @param color The legacy ChatColor to set + * @deprecated Use {@link #setColor(String)} instead + */ + @Deprecated + public void setLegacyColor(ChatColor color) { + legacyColor = color; + } + /** * @return The list of styles */ diff --git a/src/main/java/me/clip/placeholderapi/listeners/ServerLoadEventListener.java b/src/main/java/me/clip/placeholderapi/listeners/ServerLoadEventListener.java index 9de1af2..b76d2ef 100644 --- a/src/main/java/me/clip/placeholderapi/listeners/ServerLoadEventListener.java +++ b/src/main/java/me/clip/placeholderapi/listeners/ServerLoadEventListener.java @@ -28,34 +28,31 @@ import org.bukkit.event.Listener; import org.bukkit.event.server.ServerLoadEvent; import org.jetbrains.annotations.NotNull; -public final class ServerLoadEventListener implements Listener -{ +public final class ServerLoadEventListener implements Listener { - @NotNull - private final PlaceholderAPIPlugin plugin; + @NotNull + private final PlaceholderAPIPlugin plugin; - public ServerLoadEventListener(@NotNull final PlaceholderAPIPlugin plugin) - { - this.plugin = plugin; + public ServerLoadEventListener(@NotNull final PlaceholderAPIPlugin plugin) { + this.plugin = plugin; - Bukkit.getPluginManager().registerEvents(this, plugin); - } + Bukkit.getPluginManager().registerEvents(this, plugin); + } - /** - * This method will be called when the server is first loaded - *

- * The goal of the method is to register all the expansions as soon as possible - * especially before players can join - *

- * This will ensure no issues with expansions and hooks. - * - * @param event the server load event - */ - @EventHandler - public void onServerLoad(@NotNull final ServerLoadEvent event) - { - HandlerList.unregisterAll(this); - plugin.getLocalExpansionManager().load(Bukkit.getConsoleSender()); - } + /** + * This method will be called when the server is first loaded + *

+ * The goal of the method is to register all the expansions as soon as possible especially before + * players can join + *

+ * This will ensure no issues with expansions and hooks. + * + * @param event the server load event + */ + @EventHandler + public void onServerLoad(@NotNull final ServerLoadEvent event) { + HandlerList.unregisterAll(this); + plugin.getLocalExpansionManager().load(Bukkit.getConsoleSender()); + } } diff --git a/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java b/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java index 13a5ca2..f8ad649 100644 --- a/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java +++ b/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java @@ -20,181 +20,155 @@ package me.clip.placeholderapi.replacer; +import java.util.function.Function; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.function.Function; +public final class CharsReplacer implements Replacer { -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; - } + 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()); + @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(); + final StringBuilder identifier = new StringBuilder(); + final StringBuilder parameters = new StringBuilder(); - for (int i = 0; i < chars.length; i++) - { - final char l = chars[i]; + for (int i = 0; i < chars.length; i++) { + final char l = chars[i]; - if (l == '&' && ++i < chars.length) - { - final char c = Character.toLowerCase(chars[i]); + if (l == '&' && ++i < chars.length) { + final char c = Character.toLowerCase(chars[i]); - if (c != '0' && c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8' && c != '9' && c != 'a' && c != 'b' && c != 'c' && c != 'd' && c != 'e' && c != 'f' && c != 'k' && c != 'l' && c != 'm' && c != 'o' && c != 'r' && c != 'x') - { - builder.append(l).append(chars[i]); - } - else - { - builder.append(ChatColor.COLOR_CHAR); + if (c != '0' && c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' + && c != '7' && c != '8' && c != '9' && c != 'a' && c != 'b' && c != 'c' && c != 'd' + && c != 'e' && c != 'f' && c != 'k' && c != 'l' && c != 'm' && c != 'o' && c != 'r' + && c != 'x') { + builder.append(l).append(chars[i]); + } else { + builder.append(ChatColor.COLOR_CHAR); - if (c != 'x') - { - builder.append(chars[i]); - continue; - } + if (c != 'x') { + builder.append(chars[i]); + continue; + } - if ((i > 1 && chars[i - 2] == '\\') /*allow escaping &x*/) - { - builder.setLength(builder.length() - 2); - builder.append('&').append(chars[i]); - continue; - } + if ((i > 1 && chars[i - 2] == '\\') /*allow escaping &x*/) { + builder.setLength(builder.length() - 2); + builder.append('&').append(chars[i]); + continue; + } - builder.append(c); + builder.append(c); - int j = 0; - while (++j <= 6) - { - if (i + j >= chars.length) - { - break; - } + int j = 0; + while (++j <= 6) { + if (i + j >= chars.length) { + break; + } - final char x = chars[i + j]; - builder.append(ChatColor.COLOR_CHAR).append(x); - } + final char x = chars[i + j]; + builder.append(ChatColor.COLOR_CHAR).append(x); + } - if (j == 7) - { - i += 6; - } - else - { - builder.setLength(builder.length() - (j * 2)); // undo &x parsing - } - } - continue; - } + if (j == 7) { + i += 6; + } else { + builder.setLength(builder.length() - (j * 2)); // undo &x parsing + } + } + continue; + } - if (l != closure.head || i + 1 >= chars.length) - { - builder.append(l); - continue; - } + if (l != closure.head || i + 1 >= chars.length) { + builder.append(l); + continue; + } - boolean identified = false; - boolean oopsitsbad = true; + boolean identified = false; + boolean oopsitsbad = true; - while (++i < chars.length) - { - final char p = chars[i]; + while (++i < chars.length) { + final char p = chars[i]; - if (p == ' ' && !identified) - { - break; - } - if (p == closure.tail) - { - oopsitsbad = false; - break; - } + if (p == ' ' && !identified) { + break; + } + if (p == closure.tail) { + oopsitsbad = false; + break; + } - if (p == '_' && !identified) - { - identified = true; - continue; - } + if (p == '_' && !identified) { + identified = true; + continue; + } - if (identified) - { - parameters.append(p); - } - else - { - identifier.append(p); - } - } + if (identified) { + parameters.append(p); + } else { + identifier.append(p); + } + } - final String identifierString = identifier.toString().toLowerCase(); - final String parametersString = parameters.toString(); + final String identifierString = identifier.toString().toLowerCase(); + final String parametersString = parameters.toString(); - identifier.setLength(0); - parameters.setLength(0); + identifier.setLength(0); + parameters.setLength(0); - if (oopsitsbad) - { - builder.append(closure.head).append(identifierString); + if (oopsitsbad) { + builder.append(closure.head).append(identifierString); - if (identified) - { - builder.append('_').append(parametersString); - } + if (identified) { + builder.append('_').append(parametersString); + } - builder.append(' '); - continue; - } + builder.append(' '); + continue; + } - final PlaceholderExpansion placeholder = lookup.apply(identifierString); - if (placeholder == null) - { - builder.append(closure.head).append(identifierString); + final PlaceholderExpansion placeholder = lookup.apply(identifierString); + if (placeholder == null) { + builder.append(closure.head).append(identifierString); - if (identified) - { - builder.append('_'); - } + if (identified) { + builder.append('_'); + } - builder.append(parametersString).append(closure.tail); - continue; - } + builder.append(parametersString).append(closure.tail); + continue; + } - final String replacement = placeholder.onRequest(player, parametersString); - if (replacement == null) - { - builder.append(closure.head).append(identifierString); + final String replacement = placeholder.onRequest(player, parametersString); + if (replacement == null) { + builder.append(closure.head).append(identifierString); - if (identified) - { - builder.append('_'); - } + if (identified) { + builder.append('_'); + } - builder.append(parametersString).append(closure.tail); - continue; - } + builder.append(parametersString).append(closure.tail); + continue; + } - builder.append(ChatColor.translateAlternateColorCodes('&', replacement)); - } + builder.append(ChatColor.translateAlternateColorCodes('&', replacement)); + } - return builder.toString(); - } + return builder.toString(); + } } diff --git a/src/main/java/me/clip/placeholderapi/replacer/RegexReplacer.java b/src/main/java/me/clip/placeholderapi/replacer/RegexReplacer.java index 44c9aa7..3e3bee5 100644 --- a/src/main/java/me/clip/placeholderapi/replacer/RegexReplacer.java +++ b/src/main/java/me/clip/placeholderapi/replacer/RegexReplacer.java @@ -20,57 +20,53 @@ package me.clip.placeholderapi.replacer; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.function.Function; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +public final class RegexReplacer implements Replacer { -public final class RegexReplacer implements Replacer -{ + @NotNull + private final Pattern pattern; - @NotNull - private final Pattern pattern; - - public RegexReplacer(@NotNull final Closure closure) - { - this.pattern = Pattern.compile(String.format("\\%s((?[a-zA-Z0-9]+)_)(?[^%s%s]+)\\%s", closure.head, closure.head, closure.tail, closure.tail)); - } + public RegexReplacer(@NotNull final Closure closure) { + this.pattern = Pattern.compile(String + .format("\\%s((?[a-zA-Z0-9]+)_)(?[^%s%s]+)\\%s", closure.head, + closure.head, closure.tail, closure.tail)); + } - @NotNull - @Override - public String apply(@NotNull final String text, @Nullable final OfflinePlayer player, @NotNull final Function lookup) - { - final Matcher matcher = pattern.matcher(text); - if (!matcher.find()) - { - return text; - } + @NotNull + @Override + public String apply(@NotNull final String text, @Nullable final OfflinePlayer player, + @NotNull final Function lookup) { + final Matcher matcher = pattern.matcher(text); + if (!matcher.find()) { + return text; + } - final StringBuffer builder = new StringBuffer(); + final StringBuffer builder = new StringBuffer(); - do - { - final String identifier = matcher.group("identifier"); - final String parameters = matcher.group("parameters"); + do { + final String identifier = matcher.group("identifier"); + final String parameters = matcher.group("parameters"); - final PlaceholderExpansion expansion = lookup.apply(identifier); - if (expansion == null) - { - continue; - } + final PlaceholderExpansion expansion = lookup.apply(identifier); + if (expansion == null) { + continue; + } - final String requested = expansion.onRequest(player, parameters); - matcher.appendReplacement(builder, requested != null ? requested : matcher.group(0)); - } - while (matcher.find()); + final String requested = expansion.onRequest(player, parameters); + matcher.appendReplacement(builder, requested != null ? requested : matcher.group(0)); + } + while (matcher.find()); - return ChatColor.translateAlternateColorCodes('&', matcher.appendTail(builder).toString()); - } + return ChatColor.translateAlternateColorCodes('&', matcher.appendTail(builder).toString()); + } } diff --git a/src/main/java/me/clip/placeholderapi/replacer/Replacer.java b/src/main/java/me/clip/placeholderapi/replacer/Replacer.java index 04b24b7..d25402e 100644 --- a/src/main/java/me/clip/placeholderapi/replacer/Replacer.java +++ b/src/main/java/me/clip/placeholderapi/replacer/Replacer.java @@ -20,33 +20,30 @@ 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; import org.jetbrains.annotations.Nullable; -import java.util.function.Function; +public interface Replacer { -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/updatechecker/UpdateChecker.java b/src/main/java/me/clip/placeholderapi/updatechecker/UpdateChecker.java index 723e695..206dcd1 100644 --- a/src/main/java/me/clip/placeholderapi/updatechecker/UpdateChecker.java +++ b/src/main/java/me/clip/placeholderapi/updatechecker/UpdateChecker.java @@ -20,6 +20,10 @@ package me.clip.placeholderapi.updatechecker; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import javax.net.ssl.HttpsURLConnection; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.util.Msg; import org.bukkit.Bukkit; @@ -28,90 +32,85 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; -import javax.net.ssl.HttpsURLConnection; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URL; - public class UpdateChecker implements Listener { - private final int RESOURCE_ID = 6245; - private final PlaceholderAPIPlugin plugin; - private final String pluginVersion; - private String spigotVersion; - private boolean updateAvailable; + private final int RESOURCE_ID = 6245; + private final PlaceholderAPIPlugin plugin; + private final String pluginVersion; + private String spigotVersion; + private boolean updateAvailable; - public UpdateChecker(PlaceholderAPIPlugin i) { - plugin = i; - pluginVersion = i.getDescription().getVersion(); + public UpdateChecker(PlaceholderAPIPlugin i) { + plugin = i; + pluginVersion = i.getDescription().getVersion(); + } + + public boolean hasUpdateAvailable() { + return updateAvailable; + } + + public String getSpigotVersion() { + return spigotVersion; + } + + public void fetch() { + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + try { + HttpsURLConnection con = (HttpsURLConnection) new URL( + "https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID).openConnection(); + con.setRequestMethod("GET"); + spigotVersion = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine(); + } catch (Exception ex) { + plugin.getLogger().info("Failed to check for updates on spigot."); + return; + } + + if (spigotVersion == null || spigotVersion.isEmpty()) { + return; + } + + updateAvailable = spigotIsNewer(); + + if (!updateAvailable) { + return; + } + + Bukkit.getScheduler().runTask(plugin, () -> { + plugin.getLogger() + .info("An update for PlaceholderAPI (v" + getSpigotVersion() + ") is available at:"); + plugin.getLogger() + .info("https://www.spigotmc.org/resources/placeholderapi." + RESOURCE_ID + "/"); + Bukkit.getPluginManager().registerEvents(this, plugin); + }); + }); + } + + private boolean spigotIsNewer() { + if (spigotVersion == null || spigotVersion.isEmpty()) { + return false; } - public boolean hasUpdateAvailable() { - return updateAvailable; + String plV = toReadable(pluginVersion); + String spV = toReadable(spigotVersion); + return plV.compareTo(spV) < 0; + } + + private String toReadable(String version) { + if (version.contains("-DEV-")) { + version = version.split("-DEV-")[0]; } - public String getSpigotVersion() { - return spigotVersion; - } - - public void fetch() { - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { - try { - HttpsURLConnection con = (HttpsURLConnection) new URL( - "https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID).openConnection(); - con.setRequestMethod("GET"); - spigotVersion = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine(); - } catch (Exception ex) { - plugin.getLogger().info("Failed to check for updates on spigot."); - return; - } - - if (spigotVersion == null || spigotVersion.isEmpty()) { - return; - } - - updateAvailable = spigotIsNewer(); - - if (!updateAvailable) { - return; - } - - Bukkit.getScheduler().runTask(plugin, () -> { - plugin.getLogger() - .info("An update for PlaceholderAPI (v" + getSpigotVersion() + ") is available at:"); - plugin.getLogger() - .info("https://www.spigotmc.org/resources/placeholderapi." + RESOURCE_ID + "/"); - Bukkit.getPluginManager().registerEvents(this, plugin); - }); - }); - } - - private boolean spigotIsNewer() { - if (spigotVersion == null || spigotVersion.isEmpty()) { - return false; - } - - String plV = toReadable(pluginVersion); - String spV = toReadable(spigotVersion); - return plV.compareTo(spV) < 0; - } - - private String toReadable(String version) { - if (version.contains("-DEV-")) { - version = version.split("-DEV-")[0]; - } - - return version.replaceAll("\\.", ""); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onJoin(PlayerJoinEvent e) { - if (e.getPlayer().hasPermission("placeholderapi.updatenotify")) { - Msg.msg(e.getPlayer(), - "&bAn update for &fPlaceholder&7API &e(&fPlaceholder&7API &fv" + getSpigotVersion() - + "&e)" - , "&bis available at &ehttps://www.spigotmc.org/resources/placeholderapi." + RESOURCE_ID - + "/"); - } + return version.replaceAll("\\.", ""); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onJoin(PlayerJoinEvent e) { + if (e.getPlayer().hasPermission("placeholderapi.updatenotify")) { + Msg.msg(e.getPlayer(), + "&bAn update for &fPlaceholder&7API &e(&fPlaceholder&7API &fv" + getSpigotVersion() + + "&e)" + , "&bis available at &ehttps://www.spigotmc.org/resources/placeholderapi." + RESOURCE_ID + + "/"); } + } } diff --git a/src/main/java/me/clip/placeholderapi/util/FileUtil.java b/src/main/java/me/clip/placeholderapi/util/FileUtil.java index 81fd690..9741a0d 100644 --- a/src/main/java/me/clip/placeholderapi/util/FileUtil.java +++ b/src/main/java/me/clip/placeholderapi/util/FileUtil.java @@ -20,9 +20,6 @@ package me.clip.placeholderapi.util; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -31,54 +28,48 @@ import java.util.ArrayList; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -public class FileUtil -{ +public class FileUtil { - @Nullable - public static Class findClass(@NotNull final File file, @NotNull final Class clazz) throws IOException, ClassNotFoundException - { - if (!file.exists()) - { - return null; - } + @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 URL jar = file.toURI().toURL(); - final List matches = new ArrayList<>(); - final List> classes = new ArrayList<>(); + final List matches = new ArrayList<>(); + final List> classes = new ArrayList<>(); + try (final JarInputStream stream = new JarInputStream( + jar.openStream()); final URLClassLoader loader = new URLClassLoader(new URL[]{jar}, + clazz.getClassLoader())) { + JarEntry entry; + while ((entry = stream.getNextJarEntry()) != null) { + final String name = entry.getName(); + if (name == null || name.isEmpty() || !name.endsWith(".class")) { + continue; + } - try (final JarInputStream stream = new JarInputStream(jar.openStream()); final URLClassLoader loader = new URLClassLoader(new URL[]{jar}, clazz.getClassLoader())) - { - JarEntry entry; - while ((entry = stream.getNextJarEntry()) != null) - { - final String name = entry.getName(); - if (name == null || name.isEmpty() || !name.endsWith(".class")) - { - continue; - } + matches.add(name.substring(0, name.lastIndexOf('.')).replace('/', '.')); + } - 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) { + } + } + } - 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) - { } - } - } - - return classes.isEmpty() ? null : classes.get(0); - } + return classes.isEmpty() ? null : 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 ca94e5d..1d959c2 100644 --- a/src/main/java/me/clip/placeholderapi/util/Format.java +++ b/src/main/java/me/clip/placeholderapi/util/Format.java @@ -20,11 +20,6 @@ package me.clip.placeholderapi.util; -import org.jetbrains.annotations.NotNull; - -import java.util.List; -import java.util.Optional; - import static java.lang.Math.max; import static java.lang.Math.min; import static java.util.Arrays.stream; @@ -32,47 +27,44 @@ import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; +import java.util.List; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + /** * For the record, I am not sorry. */ -public final class Format -{ +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())); + } - public enum Align - { - LEFT, RIGHT - } + @NotNull + private static String buildFormat(@NotNull final Align align, @NotNull 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 - 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, @NotNull 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()); - } + 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 8b431bb..01a3586 100644 --- a/src/main/java/me/clip/placeholderapi/util/Futures.java +++ b/src/main/java/me/clip/placeholderapi/util/Futures.java @@ -20,10 +20,6 @@ package me.clip.placeholderapi.util; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -31,53 +27,51 @@ import java.util.function.BiConsumer; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; -public final class Futures -{ +public final class Futures { - private Futures() - {} + private Futures() {} - public static void onMainThread(@NotNull final Plugin plugin, @NotNull final CompletableFuture future, @NotNull final BiConsumer consumer) - { - future.whenComplete((value, exception) -> { - if (Bukkit.isPrimaryThread()) - { - consumer.accept(value, exception); - } - else - { - Bukkit.getScheduler().runTask(plugin, () -> consumer.accept(value, exception)); - } - }); - } + public static void onMainThread(@NotNull final Plugin plugin, + @NotNull final CompletableFuture future, + @NotNull final BiConsumer consumer) { + future.whenComplete((value, exception) -> { + if (Bukkit.isPrimaryThread()) { + consumer.accept(value, exception); + } else { + Bukkit.getScheduler().runTask(plugin, () -> 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 676c3c4..702b251 100644 --- a/src/main/java/me/clip/placeholderapi/util/Msg.java +++ b/src/main/java/me/clip/placeholderapi/util/Msg.java @@ -20,40 +20,34 @@ package me.clip.placeholderapi.util; +import java.util.Arrays; +import java.util.stream.Collectors; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; -import java.util.Arrays; -import java.util.stream.Collectors; +public final class Msg { -public final class Msg -{ + public static void msg(@NotNull final CommandSender sender, @NotNull final String... messages) { + if (messages.length == 0) { + return; + } - 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"))); + } - 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 broadcast(@NotNull final String... messages) - { - if (messages.length == 0) - { - return; - } + Bukkit.broadcastMessage( + Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n"))); + } - Bukkit.broadcastMessage(Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n"))); - } - - public static String color(@NotNull final String text) - { - return ChatColor.translateAlternateColorCodes('&', text); - } + 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 89d38bf..e0b9717 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 084a962..41a4a4e 100644 --- a/src/main/java/me/clip/placeholderapi/util/TimeUtil.java +++ b/src/main/java/me/clip/placeholderapi/util/TimeUtil.java @@ -25,146 +25,147 @@ import java.time.temporal.ChronoUnit; public class TimeUtil { - public static String getRemaining(int seconds, TimeFormat type) { - if (seconds < 60) { - switch (type) { - case DAYS: - case HOURS: - case MINUTES: - return "0"; - case SECONDS: - return String.valueOf(seconds); - } + public static String getRemaining(int seconds, TimeFormat type) { + if (seconds < 60) { + switch (type) { + case DAYS: + case HOURS: + case MINUTES: + return "0"; + case SECONDS: + return String.valueOf(seconds); + } - return String.valueOf(seconds); - } - - int minutes = seconds / 60; - int s = 60 * minutes; - int secondsLeft = seconds - s; - - if (minutes < 60) { - switch (type) { - case DAYS: - case HOURS: - return "0"; - case MINUTES: - return String.valueOf(minutes); - case SECONDS: - return String.valueOf(secondsLeft); - } - - return String.valueOf(seconds); - } - - if (minutes < 1440) { - int hours = minutes / 60; - int inMins = 60 * hours; - int leftOver = minutes - inMins; - - switch (type) { - case DAYS: - return "0"; - case HOURS: - return String.valueOf(hours); - case MINUTES: - return String.valueOf(leftOver); - case SECONDS: - return String.valueOf(secondsLeft); - } - - return String.valueOf(seconds); - } - - int days = minutes / 1440; - int inMins = 1440 * days; - int leftOver = minutes - inMins; - - if (leftOver < 60) { - switch (type) { - case DAYS: - return String.valueOf(days); - case HOURS: - return String.valueOf(0); - case MINUTES: - return String.valueOf(leftOver); - case SECONDS: - return String.valueOf(secondsLeft); - } - - return String.valueOf(seconds); - - } else { - int hours = leftOver / 60; - int hoursInMins = 60 * hours; - int minsLeft = leftOver - hoursInMins; - - switch (type) { - case DAYS: - return String.valueOf(days); - case HOURS: - return String.valueOf(hours); - case MINUTES: - return String.valueOf(minsLeft); - case SECONDS: - return String.valueOf(secondsLeft); - } - - return String.valueOf(seconds); - } + return String.valueOf(seconds); } - public static String getTime(int seconds) { - return getTime(Duration.ofSeconds(seconds)); + int minutes = seconds / 60; + int s = 60 * minutes; + int secondsLeft = seconds - s; + + if (minutes < 60) { + switch (type) { + case DAYS: + case HOURS: + return "0"; + case MINUTES: + return String.valueOf(minutes); + case SECONDS: + return String.valueOf(secondsLeft); + } + + return String.valueOf(seconds); } - /** - * 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) { - final StringBuilder builder = new StringBuilder(); + if (minutes < 1440) { + int hours = minutes / 60; + int inMins = 60 * hours; + int leftOver = minutes - inMins; - long seconds = duration.getSeconds(); - long minutes = seconds / 60; - long hours = minutes / 60; - long days = hours / 24; + switch (type) { + case DAYS: + return "0"; + case HOURS: + return String.valueOf(hours); + case MINUTES: + return String.valueOf(leftOver); + case SECONDS: + return String.valueOf(secondsLeft); + } - seconds %= 60; - minutes %= 60; - hours %= 60; - days %= 24; - - if (seconds > 0) { - builder.insert(0, seconds + "s"); - } - - if (minutes > 0) { - if (builder.length() > 0) { - builder.insert(0, ' '); - } - - builder.insert(0, minutes + "m"); - } - - if (hours > 0) { - if (builder.length() > 0) { - builder.insert(0, ' '); - } - - builder.insert(0, hours + "h"); - } - - if (days > 0) { - if (builder.length() > 0) { - builder.insert(0, ' '); - } - - builder.insert(0, days + "d"); - } - - return builder.toString(); + return String.valueOf(seconds); } + + int days = minutes / 1440; + int inMins = 1440 * days; + int leftOver = minutes - inMins; + + if (leftOver < 60) { + switch (type) { + case DAYS: + return String.valueOf(days); + case HOURS: + return String.valueOf(0); + case MINUTES: + return String.valueOf(leftOver); + case SECONDS: + return String.valueOf(secondsLeft); + } + + return String.valueOf(seconds); + + } else { + int hours = leftOver / 60; + int hoursInMins = 60 * hours; + int minsLeft = leftOver - hoursInMins; + + switch (type) { + case DAYS: + return String.valueOf(days); + case HOURS: + return String.valueOf(hours); + case MINUTES: + return String.valueOf(minsLeft); + case SECONDS: + return String.valueOf(secondsLeft); + } + + return String.valueOf(seconds); + } + } + + public static String getTime(int seconds) { + return getTime(Duration.ofSeconds(seconds)); + } + + /** + * 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) { + final StringBuilder builder = new StringBuilder(); + + long seconds = duration.getSeconds(); + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + + seconds %= 60; + minutes %= 60; + hours %= 60; + days %= 24; + + if (seconds > 0) { + builder.insert(0, seconds + "s"); + } + + if (minutes > 0) { + if (builder.length() > 0) { + builder.insert(0, ' '); + } + + builder.insert(0, minutes + "m"); + } + + if (hours > 0) { + if (builder.length() > 0) { + builder.insert(0, ' '); + } + + builder.insert(0, hours + "h"); + } + + if (days > 0) { + if (builder.length() > 0) { + builder.insert(0, ' '); + } + + builder.insert(0, days + "d"); + } + + return builder.toString(); + } } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 9420f1d..44295c9 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -21,15 +21,15 @@ permissions: placeholderapi.admin: description: "Ability to use all PAPI commands" children: - placeholderapi.help: true - placeholderapi.info: true - placeholderapi.list: true - placeholderapi.parse: true - placeholderapi.reload: true - placeholderapi.version: true - placeholderapi.register: true - placeholderapi.unregister: true - placeholderapi.updatenotify: true + placeholderapi.help: true + placeholderapi.info: true + placeholderapi.list: true + placeholderapi.parse: true + placeholderapi.reload: true + placeholderapi.version: true + placeholderapi.register: true + placeholderapi.unregister: true + placeholderapi.updatenotify: true placeholderapi.ecloud.*: description: "Ability to use all PAPI ecloud commands" children: diff --git a/src/test/java/me/clip/placeholderapi/Values.java b/src/test/java/me/clip/placeholderapi/Values.java index d0c31ce..73d26bc 100644 --- a/src/test/java/me/clip/placeholderapi/Values.java +++ b/src/test/java/me/clip/placeholderapi/Values.java @@ -29,75 +29,67 @@ import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public interface Values -{ +public interface Values { - String SMALL_TEXT = "My name is %player_name%"; - String LARGE_TEXT = "My name is %player_name% and my location is (%player_x%, %player_y%, %player_z%), this placeholder is invalid %server_name%"; + String SMALL_TEXT = "My name is %player_name%"; + String LARGE_TEXT = "My name is %player_name% and my location is (%player_x%, %player_y%, %player_z%), this placeholder is invalid %server_name%"; - ImmutableMap PLACEHOLDERS = ImmutableMap.builder() - .put("player", new MockPlayerPlaceholderExpansion()) - .build(); + ImmutableMap PLACEHOLDERS = ImmutableMap.builder() + .put("player", new MockPlayerPlaceholderExpansion()) + .build(); - Replacer CHARS_REPLACER = new CharsReplacer(Replacer.Closure.PERCENT); - Replacer REGEX_REPLACER = new RegexReplacer(Replacer.Closure.PERCENT); + Replacer CHARS_REPLACER = new CharsReplacer(Replacer.Closure.PERCENT); + Replacer REGEX_REPLACER = new RegexReplacer(Replacer.Closure.PERCENT); - final class MockPlayerPlaceholderExpansion extends PlaceholderExpansion - { + final class MockPlayerPlaceholderExpansion extends PlaceholderExpansion { - public static final String PLAYER_X = "10"; - public static final String PLAYER_Y = "20"; - public static final String PLAYER_Z = "30"; - public static final String PLAYER_NAME = "Sxtanna"; + public static final String PLAYER_X = "10"; + public static final String PLAYER_Y = "20"; + public static final String PLAYER_Z = "30"; + public static final String PLAYER_NAME = "Sxtanna"; - @NotNull - @Override - public String getIdentifier() - { - return "player"; - } + @NotNull + @Override + public String getIdentifier() { + return "player"; + } - @NotNull - @Override - public String getAuthor() - { - return "Sxtanna"; - } + @NotNull + @Override + public String getAuthor() { + return "Sxtanna"; + } - @NotNull - @Override - public String getVersion() - { - return "1.0"; - } + @NotNull + @Override + public String getVersion() { + return "1.0"; + } - @Override - public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params) - { - final String[] parts = params.split("_"); - if (parts.length == 0) - { - return null; - } + @Override + public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params) { + final String[] parts = params.split("_"); + if (parts.length == 0) { + return null; + } - switch (parts[0]) - { - case "name": - return PLAYER_NAME; - case "x": - return PLAYER_X; - case "y": - return PLAYER_Y; - case "z": - return PLAYER_Z; - } + switch (parts[0]) { + case "name": + return PLAYER_NAME; + case "x": + return PLAYER_X; + case "y": + return PLAYER_Y; + case "z": + return PLAYER_Z; + } - return null; - } + return null; + } - } + } } diff --git a/src/test/java/me/clip/placeholderapi/replacer/ReplacerBenchmarks.java b/src/test/java/me/clip/placeholderapi/replacer/ReplacerBenchmarks.java index 1f53b4d..2afc016 100644 --- a/src/test/java/me/clip/placeholderapi/replacer/ReplacerBenchmarks.java +++ b/src/test/java/me/clip/placeholderapi/replacer/ReplacerBenchmarks.java @@ -23,31 +23,26 @@ package me.clip.placeholderapi.replacer; import me.clip.placeholderapi.Values; import org.openjdk.jmh.annotations.Benchmark; -public class ReplacerBenchmarks -{ +public class ReplacerBenchmarks { - @Benchmark - public void measureCharsReplacerSmallText() - { - Values.CHARS_REPLACER.apply(Values.SMALL_TEXT, null, Values.PLACEHOLDERS::get); - } + @Benchmark + public void measureCharsReplacerSmallText() { + Values.CHARS_REPLACER.apply(Values.SMALL_TEXT, null, Values.PLACEHOLDERS::get); + } - @Benchmark - public void measureRegexReplacerSmallText() - { - Values.REGEX_REPLACER.apply(Values.SMALL_TEXT, null, Values.PLACEHOLDERS::get); - } + @Benchmark + public void measureRegexReplacerSmallText() { + Values.REGEX_REPLACER.apply(Values.SMALL_TEXT, null, Values.PLACEHOLDERS::get); + } - @Benchmark - public void measureCharsReplacerLargeText() - { - Values.CHARS_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get); - } + @Benchmark + public void measureCharsReplacerLargeText() { + Values.CHARS_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get); + } - @Benchmark - public void measureRegexReplacerLargeText() - { - Values.REGEX_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get); - } + @Benchmark + public void measureRegexReplacerLargeText() { + Values.REGEX_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get); + } } \ No newline at end of file diff --git a/src/test/java/me/clip/placeholderapi/replacer/ReplacerUnitTester.java b/src/test/java/me/clip/placeholderapi/replacer/ReplacerUnitTester.java index 6dffa48..09524f3 100644 --- a/src/test/java/me/clip/placeholderapi/replacer/ReplacerUnitTester.java +++ b/src/test/java/me/clip/placeholderapi/replacer/ReplacerUnitTester.java @@ -20,76 +20,80 @@ package me.clip.placeholderapi.replacer; -import me.clip.placeholderapi.Values; -import org.junit.jupiter.api.Test; - import static me.clip.placeholderapi.Values.MockPlayerPlaceholderExpansion.PLAYER_NAME; import static me.clip.placeholderapi.Values.MockPlayerPlaceholderExpansion.PLAYER_X; import static me.clip.placeholderapi.Values.MockPlayerPlaceholderExpansion.PLAYER_Y; import static me.clip.placeholderapi.Values.MockPlayerPlaceholderExpansion.PLAYER_Z; import static org.junit.jupiter.api.Assertions.assertEquals; -public final class ReplacerUnitTester -{ +import me.clip.placeholderapi.Values; +import org.junit.jupiter.api.Test; - @Test - void testCharsReplacerProducesExpectedSingleValue() - { - assertEquals(PLAYER_NAME, Values.CHARS_REPLACER.apply("%player_name%", null, Values.PLACEHOLDERS::get)); - } +public final class ReplacerUnitTester { - @Test - void testRegexReplacerProducesExpectedSingleValue() - { - assertEquals(PLAYER_NAME, Values.REGEX_REPLACER.apply("%player_name%", null, Values.PLACEHOLDERS::get)); - } + @Test + void testCharsReplacerProducesExpectedSingleValue() { + assertEquals(PLAYER_NAME, + Values.CHARS_REPLACER.apply("%player_name%", null, Values.PLACEHOLDERS::get)); + } - @Test - void testCharsReplacerProducesExpectedSentence() - { - assertEquals(String.format("My name is %s and my location is (%s, %s, %s), this placeholder is invalid %%server_name%%", PLAYER_NAME, PLAYER_X, PLAYER_Y, PLAYER_Z), Values.CHARS_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get)); - } + @Test + void testRegexReplacerProducesExpectedSingleValue() { + assertEquals(PLAYER_NAME, + Values.REGEX_REPLACER.apply("%player_name%", null, Values.PLACEHOLDERS::get)); + } - @Test - void testRegexReplacerProducesExpectedSentence() - { - assertEquals(String.format("My name is %s and my location is (%s, %s, %s), this placeholder is invalid %%server_name%%", PLAYER_NAME, PLAYER_X, PLAYER_Y, PLAYER_Z), Values.REGEX_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get)); - } + @Test + void testCharsReplacerProducesExpectedSentence() { + assertEquals(String.format( + "My name is %s and my location is (%s, %s, %s), this placeholder is invalid %%server_name%%", + PLAYER_NAME, PLAYER_X, PLAYER_Y, PLAYER_Z), + Values.CHARS_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get)); + } - @Test - void testResultsAreTheSameAsReplacement() - { - final String resultChars = Values.CHARS_REPLACER.apply("%player_name%", null, Values.PLACEHOLDERS::get); - final String resultRegex = Values.REGEX_REPLACER.apply("%player_name%", null, Values.PLACEHOLDERS::get); + @Test + void testRegexReplacerProducesExpectedSentence() { + assertEquals(String.format( + "My name is %s and my location is (%s, %s, %s), this placeholder is invalid %%server_name%%", + PLAYER_NAME, PLAYER_X, PLAYER_Y, PLAYER_Z), + Values.REGEX_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get)); + } - assertEquals(resultChars, resultRegex); + @Test + void testResultsAreTheSameAsReplacement() { + final String resultChars = Values.CHARS_REPLACER + .apply("%player_name%", null, Values.PLACEHOLDERS::get); + final String resultRegex = Values.REGEX_REPLACER + .apply("%player_name%", null, Values.PLACEHOLDERS::get); - assertEquals(PLAYER_NAME, resultChars); - } + assertEquals(resultChars, resultRegex); - @Test - void testResultsAreTheSameNoReplacement() - { - final String resultChars = Values.CHARS_REPLACER.apply("%player_location%", null, Values.PLACEHOLDERS::get); - final String resultRegex = Values.REGEX_REPLACER.apply("%player_location%", null, Values.PLACEHOLDERS::get); + assertEquals(PLAYER_NAME, resultChars); + } - assertEquals(resultChars, resultRegex); - } + @Test + void testResultsAreTheSameNoReplacement() { + final String resultChars = Values.CHARS_REPLACER + .apply("%player_location%", null, Values.PLACEHOLDERS::get); + final String resultRegex = Values.REGEX_REPLACER + .apply("%player_location%", null, Values.PLACEHOLDERS::get); - @Test - void testCharsReplacerIgnoresMalformed() - { - final String text = "10% and %hello world 15%"; + assertEquals(resultChars, resultRegex); + } - assertEquals(text, Values.CHARS_REPLACER.apply(text, null, Values.PLACEHOLDERS::get)); - } + @Test + void testCharsReplacerIgnoresMalformed() { + final String text = "10% and %hello world 15%"; - @Test - void testCharsReplacerHandlesEscapedHex() - { - final String text = "\\&xffffffThis should not change."; + assertEquals(text, Values.CHARS_REPLACER.apply(text, null, Values.PLACEHOLDERS::get)); + } - assertEquals(text.substring(1), Values.CHARS_REPLACER.apply(text, null, Values.PLACEHOLDERS::get)); - } + @Test + void testCharsReplacerHandlesEscapedHex() { + final String text = "\\&xffffffThis should not change."; + + assertEquals(text.substring(1), + Values.CHARS_REPLACER.apply(text, null, Values.PLACEHOLDERS::get)); + } }