Format to Daddy code style

This commit is contained in:
extendedclip 2020-07-31 22:52:07 -04:00
parent cee6984818
commit dcc8dad4ea
60 changed files with 3481 additions and 3835 deletions

View File

@ -225,8 +225,7 @@ public final class PlaceholderAPI {
@NotNull
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2.11.0")
public static Map<String, PlaceholderHook> getPlaceholders()
{
public static Map<String, PlaceholderHook> getPlaceholders() {
return PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()
.getExpansions().stream()
.collect(Collectors.toMap(PlaceholderExpansion::getIdentifier, ex -> ex));

View File

@ -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,42 +40,31 @@ 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;
private static PlaceholderAPIPlugin instance;
static
{
static {
final String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
boolean isSpigot;
try
{
try {
Class.forName("org.spigotmc.SpigotConfig");
isSpigot = true;
}
catch (final ExceptionInInitializerError | ClassNotFoundException ignored)
{
} catch (final ExceptionInInitializerError | ClassNotFoundException ignored) {
isSpigot = false;
}
VERSION = new Version(version, isSpigot);
}
private static PlaceholderAPIPlugin instance;
@NotNull
private final PlaceholderAPIConfig config = new PlaceholderAPIConfig(this);
@ -80,139 +73,6 @@ public final class PlaceholderAPIPlugin extends JavaPlugin
@NotNull
private final CloudExpansionManager cloudExpansionManager = new CloudExpansionManager(this);
@Override
public void onLoad()
{
instance = this;
saveDefaultConfig();
}
@Override
public void onEnable()
{
setupCommand();
setupMetrics();
setupExpansions();
if (config.isCloudEnabled())
{
getCloudExpansionManager().load();
}
if (config.checkUpdates())
{
new UpdateChecker(this).fetch();
}
}
@Override
public void onDisable()
{
getCloudExpansionManager().kill();
getLocalExpansionManager().kill();
HandlerList.unregisterAll(this);
Bukkit.getScheduler().cancelTasks(this);
instance = null;
}
public void reloadConf(@NotNull final CommandSender sender)
{
getLocalExpansionManager().kill();
reloadConfig();
getLocalExpansionManager().load(sender);
if (config.isCloudEnabled())
{
getCloudExpansionManager().load();
}
else
{
getCloudExpansionManager().kill();
}
}
@NotNull
public LocalExpansionManager getLocalExpansionManager()
{
return localExpansionManager;
}
@NotNull
public CloudExpansionManager getCloudExpansionManager()
{
return cloudExpansionManager;
}
/**
* Obtain the configuration class for PlaceholderAPI.
*
* @return PlaceholderAPIConfig instance
*/
@NotNull
public PlaceholderAPIConfig getPlaceholderAPIConfig()
{
return config;
}
private void setupCommand()
{
final PluginCommand pluginCommand = getCommand("placeholderapi");
if (pluginCommand == null)
{
return;
}
final PlaceholderCommandRouter router = new PlaceholderCommandRouter(this);
pluginCommand.setExecutor(router);
pluginCommand.setTabCompleter(router);
}
private void setupMetrics()
{
final Metrics metrics = new Metrics(this);
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.AdvancedPie("expansions_used", () -> {
final Map<String, Integer> values = new HashMap<>();
for (final PlaceholderExpansion expansion : getLocalExpansionManager().getExpansions())
{
values.put(expansion.getRequiredPlugin() == null ? expansion.getIdentifier() : expansion.getRequiredPlugin(), 1);
}
return values;
}));
}
private void setupExpansions()
{
Bukkit.getPluginManager().registerEvents(getLocalExpansionManager(), this);
try
{
Class.forName("org.bukkit.event.server.ServerLoadEvent");
new ServerLoadEventListener(this);
}
catch (final 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
@ -221,20 +81,17 @@ public final class PlaceholderAPIPlugin extends JavaPlugin
* @return PlaceholderAPIPlugin instance
*/
@NotNull
public static PlaceholderAPIPlugin getInstance()
{
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()
{
public static String booleanTrue() {
return getInstance().getPlaceholderAPIConfig().booleanTrue();
}
@ -244,8 +101,7 @@ public final class PlaceholderAPIPlugin extends JavaPlugin
* @return string value of false
*/
@NotNull
public static String booleanFalse()
{
public static String booleanFalse() {
return getInstance().getPlaceholderAPIConfig().booleanFalse();
}
@ -256,23 +112,128 @@ public final class PlaceholderAPIPlugin extends JavaPlugin
* @return date format
*/
@NotNull
public static SimpleDateFormat getDateFormat()
{
try
{
public static SimpleDateFormat getDateFormat() {
try {
return new SimpleDateFormat(getInstance().getPlaceholderAPIConfig().dateFormat());
}
catch (final IllegalArgumentException ex)
{
} 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()
{
public static Version getServerVersion() {
return VERSION;
}
@Override
public void onLoad() {
instance = this;
saveDefaultConfig();
}
@Override
public void onEnable() {
setupCommand();
setupMetrics();
setupExpansions();
if (config.isCloudEnabled()) {
getCloudExpansionManager().load();
}
if (config.checkUpdates()) {
new UpdateChecker(this).fetch();
}
}
@Override
public void onDisable() {
getCloudExpansionManager().kill();
getLocalExpansionManager().kill();
HandlerList.unregisterAll(this);
Bukkit.getScheduler().cancelTasks(this);
instance = null;
}
public void reloadConf(@NotNull final CommandSender sender) {
getLocalExpansionManager().kill();
reloadConfig();
getLocalExpansionManager().load(sender);
if (config.isCloudEnabled()) {
getCloudExpansionManager().load();
} else {
getCloudExpansionManager().kill();
}
}
@NotNull
public LocalExpansionManager getLocalExpansionManager() {
return localExpansionManager;
}
@NotNull
public CloudExpansionManager getCloudExpansionManager() {
return cloudExpansionManager;
}
/**
* Obtain the configuration class for PlaceholderAPI.
*
* @return PlaceholderAPIConfig instance
*/
@NotNull
public PlaceholderAPIConfig getPlaceholderAPIConfig() {
return config;
}
private void setupCommand() {
final PluginCommand pluginCommand = getCommand("placeholderapi");
if (pluginCommand == null) {
return;
}
final PlaceholderCommandRouter router = new PlaceholderCommandRouter(this);
pluginCommand.setExecutor(router);
pluginCommand.setTabCompleter(router);
}
private void setupMetrics() {
final Metrics metrics = new Metrics(this);
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.AdvancedPie("expansions_used", () -> {
final Map<String, Integer> values = new HashMap<>();
for (final PlaceholderExpansion expansion : getLocalExpansionManager().getExpansions()) {
values.put(expansion.getRequiredPlugin() == null ? expansion.getIdentifier()
: expansion.getRequiredPlugin(), 1);
}
return values;
}));
}
private void setupExpansions() {
Bukkit.getPluginManager().registerEvents(getLocalExpansionManager(), this);
try {
Class.forName("org.bukkit.event.server.ServerLoadEvent");
new ServerLoadEventListener(this);
} catch (final ExceptionInInitializerError | ClassNotFoundException ignored) {
Bukkit.getScheduler()
.runTaskLater(this, () -> getLocalExpansionManager().load(Bukkit.getConsoleSender()), 1);
}
}
}

View File

@ -27,19 +27,17 @@ 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())
{
public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params) {
if (player != null && player.isOnline()) {
return onPlaceholderRequest((Player) player, params);
}
@ -47,12 +45,12 @@ public abstract class PlaceholderHook
}
/**
* @deprecated This method will be completely removed, please use {@link me.clip.placeholderapi.expansion.PlaceholderExpansion#onRequest(OfflinePlayer, String)}
* @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)
{
public String onPlaceholderRequest(@Nullable final Player player, @NotNull final String params) {
return null;
}

View File

@ -22,18 +22,16 @@ 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;
@ -44,75 +42,66 @@ public abstract class PlaceholderCommand
private String permission;
protected PlaceholderCommand(@NotNull final String label, @NotNull final String... alias)
{
protected PlaceholderCommand(@NotNull final String label, @NotNull final String... alias) {
this.label = label;
this.alias = Sets.newHashSet(alias);
setPermission("placeholderapi." + label);
}
@NotNull
public static Stream<PlaceholderCommand> filterByPermission(@NotNull final CommandSender sender,
@NotNull final Stream<PlaceholderCommand> commands) {
return commands.filter(
target -> target.getPermission() == null || sender.hasPermission(target.getPermission()));
}
public static void suggestByParameter(@NotNull final Stream<String> possible,
@NotNull final List<String> 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
public final String getLabel()
{
public final String getLabel() {
return label;
}
@NotNull
@Unmodifiable
public final Set<String> getAlias()
{
public final Set<String> getAlias() {
return ImmutableSet.copyOf(alias);
}
@NotNull
@Unmodifiable
public final Set<String> getLabels()
{
public final Set<String> getLabels() {
return ImmutableSet.<String>builder().add(label).addAll(alias).build();
}
@Nullable
public final String getPermission()
{
public final String getPermission() {
return permission;
}
public void setPermission(@NotNull final String 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<String> params)
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
}
public void complete(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions)
{
public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
}
@NotNull
public static Stream<PlaceholderCommand> filterByPermission(@NotNull final CommandSender sender, @NotNull final Stream<PlaceholderCommand> commands)
{
return commands.filter(target -> target.getPermission() == null || sender.hasPermission(target.getPermission()));
}
public static void suggestByParameter(@NotNull final Stream<String> possible, @NotNull final List<String> suggestions, @Nullable final String parameter)
{
if (parameter == null)
{
possible.forEach(suggestions::add);
}
else
{
possible.filter(suggestion -> suggestion.toLowerCase().startsWith(parameter.toLowerCase())).forEach(suggestions::add);
}
}
}

View File

@ -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,11 +48,7 @@ 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<PlaceholderCommand> COMMANDS = ImmutableList.of(new CommandHelp(),
@ -67,14 +70,12 @@ public final class PlaceholderCommandRouter implements CommandExecutor, TabCompl
private final Map<String, PlaceholderCommand> commands;
public PlaceholderCommandRouter(@NotNull final PlaceholderAPIPlugin plugin)
{
public PlaceholderCommandRouter(@NotNull final PlaceholderAPIPlugin plugin) {
this.plugin = plugin;
final ImmutableMap.Builder<String, PlaceholderCommand> commands = ImmutableMap.builder();
for (final PlaceholderCommand command : COMMANDS)
{
for (final PlaceholderCommand command : COMMANDS) {
command.getLabels().forEach(label -> commands.put(label, command));
}
@ -83,13 +84,11 @@ public final class PlaceholderCommandRouter implements CommandExecutor, TabCompl
@Override
public boolean onCommand(@NotNull final CommandSender sender, @NotNull final Command command, @NotNull final String alias, @NotNull final String[] args)
{
if (args.length == 0)
{
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)
{
if (fallback != null) {
fallback.evaluate(plugin, sender, "", Collections.emptyList());
}
@ -99,42 +98,42 @@ public final class PlaceholderCommandRouter implements CommandExecutor, TabCompl
final String search = args[0].toLowerCase();
final PlaceholderCommand target = commands.get(search);
if (target == null)
{
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))
{
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;
}
@Override
public List<String> onTabComplete(@NotNull final CommandSender sender, @NotNull final Command command, @NotNull final String alias, @NotNull final String[] args)
{
public List<String> onTabComplete(@NotNull final CommandSender sender,
@NotNull final Command command, @NotNull final String alias, @NotNull final String[] args) {
final List<String> suggestions = new ArrayList<>();
if (args.length > 1)
{
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;
}
final Stream<String> targets = PlaceholderCommand.filterByPermission(sender, commands.values().stream()).map(PlaceholderCommand::getLabels).flatMap(Collection::stream);
final Stream<String> 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;

View File

@ -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,16 +33,11 @@ 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<PlaceholderCommand> COMMANDS = ImmutableList.of(new CommandECloudClear(),
private static final List<PlaceholderCommand> COMMANDS = ImmutableList
.of(new CommandECloudClear(),
new CommandECloudToggle(),
new CommandECloudStatus(),
new CommandECloudUpdate(),
@ -48,9 +47,9 @@ public final class CommandECloud extends PlaceholderCommand
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
@ -58,14 +57,12 @@ public final class CommandECloud extends PlaceholderCommand
private final Map<String, PlaceholderCommand> commands;
public CommandECloud()
{
public CommandECloud() {
super("ecloud");
final ImmutableMap.Builder<String, PlaceholderCommand> commands = ImmutableMap.builder();
for (final PlaceholderCommand command : COMMANDS)
{
for (final PlaceholderCommand command : COMMANDS) {
command.getLabels().forEach(label -> commands.put(label, command));
}
@ -74,10 +71,10 @@ public final class CommandECloud extends PlaceholderCommand
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
if (params.isEmpty())
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) {
Msg.msg(sender,
"&b&lPlaceholderAPI &8- &7eCloud Help Menu &8- ",
" ",
@ -106,21 +103,19 @@ public final class CommandECloud extends PlaceholderCommand
final String search = params.get(0).toLowerCase();
final PlaceholderCommand target = commands.get(search);
if (target == null)
{
if (target == null) {
Msg.msg(sender, "&cUnknown command &7ecloud " + search);
return;
}
final String permission = target.getPermission();
if (permission != null && !permission.isEmpty() && !sender.hasPermission(permission))
{
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())
{
if (!(target instanceof CommandECloudToggle) && !plugin.getPlaceholderAPIConfig()
.isCloudEnabled()) {
Msg.msg(sender,
"&cThe eCloud Manager is not enabled!");
return;
@ -130,11 +125,12 @@ public final class CommandECloud extends PlaceholderCommand
}
@Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions)
{
if (params.size() <= 1)
{
final Stream<String> targets = filterByPermission(sender, commands.values().stream()).map(PlaceholderCommand::getLabels).flatMap(Collection::stream);
public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() <= 1) {
final Stream<String> 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
@ -143,8 +139,7 @@ public final class CommandECloud extends PlaceholderCommand
final String search = params.get(0).toLowerCase();
final PlaceholderCommand target = commands.get(search);
if (target == null)
{
if (target == null) {
return;
}

View File

@ -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,19 +28,16 @@ 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()
{
public CommandECloudClear() {
super("clear");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
plugin.getCloudExpansionManager().clean();
Msg.msg(sender,
"&aThe eCloud cache has been cleared!");

View File

@ -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,52 +31,41 @@ 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()
{
public CommandECloudDownload() {
super("download");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
if (params.isEmpty())
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> 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)
{
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)
{
if (params.size() < 2) {
version = expansion.getVersion(expansion.getLatestVersion());
if (version == null)
{
if (version == null) {
Msg.msg(sender,
"&cCould not find latest version for expansion.");
return;
}
}
else
{
} else {
version = expansion.getVersion(params.get(1));
if (version == null)
{
if (version == null) {
Msg.msg(sender,
"&cCould not find specified version: &f" + params.get(1),
"&7Available versions: &f" + expansion.getAvailableVersions());
@ -81,41 +73,43 @@ public final class CommandECloudDownload extends PlaceholderCommand
}
}
plugin.getCloudExpansionManager().downloadExpansion(expansion, version).whenComplete((file, exception) -> {
if (exception != null)
{
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(),
"&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()
.fetch(plugin.getPlaceholderAPIConfig().cloudAllowUnverifiedExpansions());
});
}
@Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions)
{
if (params.size() > 2)
{
public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 2) {
return;
}
if (params.size() <= 1)
{
final Stream<String> names = plugin.getCloudExpansionManager().getCloudExpansions().values().stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_'));
if (params.size() <= 1) {
final Stream<String> 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<CloudExpansion> expansion = plugin.getCloudExpansionManager().findCloudExpansionByName(params.get(0));
if (!expansion.isPresent())
{
final Optional<CloudExpansion> expansion = plugin.getCloudExpansionManager()
.findCloudExpansionByName(params.get(0));
if (!expansion.isPresent()) {
return;
}

View File

@ -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,31 +31,25 @@ 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()
{
public CommandECloudExpansionInfo() {
super("info");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
if (params.isEmpty())
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> 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)
{
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;
@ -71,8 +68,7 @@ public final class CommandECloudExpansionInfo extends PlaceholderCommand
.append(expansion.isVerified() ? "&a&l✔" : "&c&l❌")
.append('\n');
if (params.size() < 2)
{
if (params.size() < 2) {
builder.append("&bLatest Version: &f")
.append(expansion.getLatestVersion())
.append('\n')
@ -83,12 +79,9 @@ public final class CommandECloudExpansionInfo extends PlaceholderCommand
.append("&bRelease Notes: &f")
.append(expansion.getVersion().getReleaseNotes())
.append('\n');
}
else
{
} else {
final CloudExpansion.Version version = expansion.getVersion(params.get(1));
if (version == null)
{
if (version == null) {
Msg.msg(sender,
"&cCould not find specified version: &f" + params.get(1),
"&aVersions: &f" + expansion.getAvailableVersions());
@ -110,23 +103,23 @@ public final class CommandECloudExpansionInfo extends PlaceholderCommand
}
@Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions)
{
if (params.size() > 2)
{
public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 2) {
return;
}
if (params.size() <= 1)
{
final Stream<String> names = plugin.getCloudExpansionManager().getCloudExpansions().values().stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_'));
if (params.size() <= 1) {
final Stream<String> 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<CloudExpansion> expansion = plugin.getCloudExpansionManager().findCloudExpansionByName(params.get(0));
if (!expansion.isPresent())
{
final Optional<CloudExpansion> expansion = plugin.getCloudExpansionManager()
.findCloudExpansionByName(params.get(0));
if (!expansion.isPresent()) {
return;
}

View File

@ -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,28 +52,14 @@ 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;
@NotNull
private static final Function<CloudExpansion, Object> EXPANSION_NAME =
expansion -> (expansion.shouldUpdate() ? "&6" : expansion.hasExpansion() ? "&a" : "&7") + expansion.getName();
expansion -> (expansion.shouldUpdate() ? "&6" : expansion.hasExpansion() ? "&a" : "&7")
+ expansion.getName();
@NotNull
private static final Function<CloudExpansion, Object> EXPANSION_AUTHOR =
expansion -> "&f" + expansion.getAuthor();
@ -72,43 +71,198 @@ public final class CommandECloudExpansionList extends PlaceholderCommand
expansion -> "&f" + expansion.getLatestVersion();
@NotNull
private static final Function<CloudExpansion, Object> EXPANSION_CURRENT_VERSION =
expansion -> "&f" + PlaceholderAPIPlugin.getInstance().getLocalExpansionManager().findExpansionByName(expansion.getName()).map(PlaceholderExpansion::getVersion).orElse("Unknown");
expansion -> "&f" + PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()
.findExpansionByName(expansion.getName()).map(PlaceholderExpansion::getVersion)
.orElse("Unknown");
@Unmodifiable
private static final Set<String> OPTIONS = ImmutableSet.of("all", "installed");
public CommandECloudExpansionList()
{
public CommandECloudExpansionList() {
super("list");
}
@NotNull
private static Collection<CloudExpansion> 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<CloudExpansion> getPage(@NotNull final List<CloudExpansion> expansions,
final int page) {
final int head = (page * PAGE_SIZE);
final int tail = Math.min(expansions.size(), head + PAGE_SIZE);
if (expansions.size() < head) {
return Collections.emptyList();
}
return expansions.subList(head, tail);
}
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 (page == -1) {
builder.append('\n');
return;
}
builder.append(" &bPage&7: &a")
.append(page)
.append("&r")
.append('\n');
}
@NotNull
private static JSONMessage getMessage(@NotNull final List<CloudExpansion> expansions,
final int page, final int limit, @NotNull final String target) {
final SimpleDateFormat format = PlaceholderAPIPlugin.getDateFormat();
final StringBuilder tooltip = new StringBuilder();
final JSONMessage message = JSONMessage.create();
for (int index = 0; index < expansions.size(); index++) {
final CloudExpansion expansion = expansions.get(index);
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()));
final String description = expansion.getDescription();
if (description != null && !description.isEmpty()) {
tooltip.append('\n')
.append('\n')
.append("&f")
.append(description.replace("\r", "").trim());
}
message.then(Msg.color(
"&8" + (index + ((page - 1) * PAGE_SIZE) + 1) + ".&r " + (expansion.shouldUpdate() ? "&6"
: expansion.hasExpansion() ? "&a" : "&7") + expansion.getName()));
message.tooltip(Msg.color(tooltip.toString()));
message.suggestCommand("/papi ecloud download " + expansion.getName());
if (index < expansions.size() - 1) {
message.newline();
}
tooltip.setLength(0);
}
if (limit > 1) {
message.newline();
message.then("")
.color(page > 1 ? ChatColor.GRAY : ChatColor.DARK_GRAY);
if (page > 1) {
message.runCommand("/papi ecloud list " + target + " " + (page - 1));
}
message.then(" " + page + " ").color(ChatColor.GREEN);
message.then("")
.color(page < limit ? ChatColor.GRAY : ChatColor.DARK_GRAY);
if (page < limit) {
message.runCommand("/papi ecloud list " + target + " " + (page + 1));
}
}
return message;
}
private static void addExpansionTable(@NotNull final List<CloudExpansion> expansions,
@NotNull final StringBuilder message, final int startIndex,
@NotNull final String versionTitle,
@NotNull final Function<CloudExpansion, Object> versionFunction) {
final Map<String, Function<CloudExpansion, Object>> functions = new LinkedHashMap<>();
final AtomicInteger counter = new AtomicInteger(startIndex);
functions.put("&f", expansion -> "&8" + counter.getAndIncrement() + ".");
functions.put("&9Name", EXPANSION_NAME);
functions.put("&9Author", EXPANSION_AUTHOR);
functions.put("&9Verified", EXPANSION_VERIFIED);
functions.put(versionTitle, versionFunction);
final List<List<String>> rows = new ArrayList<>();
rows.add(0, new ArrayList<>(functions.keySet()));
for (final CloudExpansion expansion : expansions) {
rows.add(functions.values().stream().map(function -> function.apply(expansion))
.map(Objects::toString).collect(Collectors.toList()));
}
final List<String> 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));
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
if (params.isEmpty())
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) {
Msg.msg(sender,
"&cYou must specify an option. [all, {author}, installed]");
return;
}
final boolean installed = params.get(0).equalsIgnoreCase("installed");
final List<CloudExpansion> expansions = Lists.newArrayList(getExpansions(params.get(0), plugin));
final List<CloudExpansion> expansions = Lists
.newArrayList(getExpansions(params.get(0), plugin));
if (expansions.isEmpty())
{
if (expansions.isEmpty()) {
Msg.msg(sender,
"&cNo expansions available to list.");
return;
}
expansions.sort(plugin.getPlaceholderAPIConfig().getExpansionSort().orElse(ExpansionSort.LATEST));
expansions
.sort(plugin.getPlaceholderAPIConfig().getExpansionSort().orElse(ExpansionSort.LATEST));
if (!(sender instanceof Player) && params.size() < 2)
{
if (!(sender instanceof Player) && params.size() < 2) {
final StringBuilder builder = new StringBuilder();
addExpansionTitle(builder, params.get(0), -1);
@ -124,16 +278,12 @@ public final class CommandECloudExpansionList extends PlaceholderCommand
final int page;
if (params.size() < 2)
{
if (params.size() < 2) {
page = 1;
}
else
{
} else {
//noinspection UnstableApiUsage
final Integer parsed = Ints.tryParse(params.get(1));
if (parsed == null)
{
if (parsed == null) {
Msg.msg(sender,
"&cPage number must be an integer.");
return;
@ -141,8 +291,7 @@ public final class CommandECloudExpansionList extends PlaceholderCommand
final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE);
if (parsed < 1 || parsed > limit)
{
if (parsed < 1 || parsed > limit) {
Msg.msg(sender,
"&cPage number must be in the range &8[&a1&7..&a" + limit + "&8]");
return;
@ -156,8 +305,7 @@ public final class CommandECloudExpansionList extends PlaceholderCommand
addExpansionTitle(builder, params.get(0), page);
if (!(sender instanceof Player))
{
if (!(sender instanceof Player)) {
addExpansionTable(values,
builder,
((page - 1) * PAGE_SIZE) + 1,
@ -178,183 +326,23 @@ public final class CommandECloudExpansionList extends PlaceholderCommand
}
@Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions)
{
if (params.size() > 2)
{
public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 2) {
return;
}
if (params.size() <= 1)
{
suggestByParameter(Sets.union(OPTIONS, plugin.getCloudExpansionManager().getCloudExpansionAuthors()).stream(), suggestions, params.isEmpty() ? null : params.get(0));
if (params.size() <= 1) {
suggestByParameter(
Sets.union(OPTIONS, plugin.getCloudExpansionManager().getCloudExpansionAuthors())
.stream(), suggestions, params.isEmpty() ? null : params.get(0));
return;
}
suggestByParameter(IntStream.rangeClosed(1, (int) Math.ceil((double) getExpansions(params.get(0), plugin).size() / PAGE_SIZE)).mapToObj(Objects::toString), suggestions, params.get(1));
}
@NotNull
private static Collection<CloudExpansion> 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<CloudExpansion> getPage(@NotNull final List<CloudExpansion> expansions, final int page)
{
final int head = (page * PAGE_SIZE);
final int tail = Math.min(expansions.size(), head + PAGE_SIZE);
if (expansions.size() < head)
{
return Collections.emptyList();
}
return expansions.subList(head, tail);
}
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 (page == -1)
{
builder.append('\n');
return;
}
builder.append(" &bPage&7: &a")
.append(page)
.append("&r")
.append('\n');
}
@NotNull
private static JSONMessage getMessage(@NotNull final List<CloudExpansion> expansions, final int page, final int limit, @NotNull final String target)
{
final SimpleDateFormat format = PlaceholderAPIPlugin.getDateFormat();
final StringBuilder tooltip = new StringBuilder();
final JSONMessage message = JSONMessage.create();
for (int index = 0; index < expansions.size(); index++)
{
final CloudExpansion expansion = expansions.get(index);
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()));
final String description = expansion.getDescription();
if (description != null && !description.isEmpty())
{
tooltip.append('\n')
.append('\n')
.append("&f")
.append(description.replace("\r", "").trim());
}
message.then(Msg.color("&8" + (index + ((page - 1) * PAGE_SIZE) + 1) + ".&r " + (expansion.shouldUpdate() ? "&6" : expansion.hasExpansion() ? "&a" : "&7") + expansion.getName()));
message.tooltip(Msg.color(tooltip.toString()));
message.suggestCommand("/papi ecloud download " + expansion.getName());
if (index < expansions.size() - 1)
{
message.newline();
}
tooltip.setLength(0);
}
if (limit > 1)
{
message.newline();
message.then("")
.color(page > 1 ? ChatColor.GRAY : ChatColor.DARK_GRAY);
if (page > 1)
{
message.runCommand("/papi ecloud list " + target + " " + (page - 1));
}
message.then(" " + page + " ").color(ChatColor.GREEN);
message.then("")
.color(page < limit ? ChatColor.GRAY : ChatColor.DARK_GRAY);
if (page < limit)
{
message.runCommand("/papi ecloud list " + target + " " + (page + 1));
}
}
return message;
}
private static void addExpansionTable(@NotNull final List<CloudExpansion> expansions, @NotNull final StringBuilder message, final int startIndex, @NotNull final String versionTitle, @NotNull final Function<CloudExpansion, Object> versionFunction)
{
final Map<String, Function<CloudExpansion, Object>> functions = new LinkedHashMap<>();
final AtomicInteger counter = new AtomicInteger(startIndex);
functions.put("&f", expansion -> "&8" + counter.getAndIncrement() + ".");
functions.put("&9Name", EXPANSION_NAME);
functions.put("&9Author", EXPANSION_AUTHOR);
functions.put("&9Verified", EXPANSION_VERIFIED);
functions.put(versionTitle, versionFunction);
final List<List<String>> rows = new ArrayList<>();
rows.add(0, new ArrayList<>(functions.keySet()));
for (final CloudExpansion expansion : expansions)
{
rows.add(functions.values().stream().map(function -> function.apply(expansion)).map(Objects::toString).collect(Collectors.toList()));
}
final List<String> 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));
}
}

View File

@ -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,57 +32,52 @@ 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()
{
public CommandECloudExpansionPlaceholders() {
super("placeholders");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
if (params.isEmpty())
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> 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)
{
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<String> placeholders = expansion.getPlaceholders();
if (placeholders == null || placeholders.isEmpty())
{
if (placeholders == null || placeholders.isEmpty()) {
Msg.msg(sender,
"&cThe expansion specified does not have placeholders listed.");
return;
}
final List<List<String>> partitions = Lists.partition(placeholders.stream().sorted().collect(Collectors.toList()), 10);
final List<List<String>> 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")));
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<String> params, @NotNull final List<String> suggestions)
{
if (params.size() > 1)
{
public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 1) {
return;
}

View File

@ -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,21 +28,19 @@ 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()
{
public CommandECloudRefresh() {
super("refresh");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
plugin.getCloudExpansionManager().clean();
plugin.getCloudExpansionManager().fetch(plugin.getPlaceholderAPIConfig().cloudAllowUnverifiedExpansions());
plugin.getCloudExpansionManager()
.fetch(plugin.getPlaceholderAPIConfig().cloudAllowUnverifiedExpansions());
Msg.msg(sender,
"&aThe eCloud manager has been refreshed!");

View File

@ -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,19 +29,16 @@ 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()
{
public CommandECloudStatus() {
super("status");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
final CloudExpansionManager manager = plugin.getCloudExpansionManager();
final int updateCount = manager.getCloudUpdateCount();
@ -49,12 +47,15 @@ public final class CommandECloudStatus extends PlaceholderCommand
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());

View File

@ -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,20 @@ 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()
{
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<String> params)
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
final boolean desiredState;
final boolean currentState = plugin.getPlaceholderAPIConfig().isCloudEnabled();
switch (alias.toLowerCase())
{
switch (alias.toLowerCase()) {
case "enable":
desiredState = true;
break;
@ -56,20 +53,16 @@ public final class CommandECloudToggle extends PlaceholderCommand
break;
}
if (desiredState == currentState)
{
if (desiredState == currentState) {
Msg.msg(sender, "&7The eCloud Manager is already " + (desiredState ? "enabled" : "disabled"));
return;
}
plugin.getPlaceholderAPIConfig().setCloudEnabled(desiredState);
if (desiredState)
{
if (desiredState) {
plugin.getCloudExpansionManager().load();
}
else
{
} else {
plugin.getCloudExpansionManager().kill();
}

View File

@ -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,30 +38,29 @@ 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()
{
public CommandECloudUpdate() {
super("update");
}
private static CompletableFuture<List<@Nullable Class<? extends PlaceholderExpansion>>> downloadAndDiscover(
@NotNull final List<CloudExpansion> 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<String> params)
{
if (params.isEmpty())
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) {
Msg.msg(sender,
"&cYou must define 'all' or the name of an expansion to update.");
return;
@ -65,32 +70,29 @@ public final class CommandECloudUpdate extends PlaceholderCommand
final List<CloudExpansion> expansions = new ArrayList<>();
// gather target expansions
if (multiple)
{
if (multiple) {
expansions.addAll(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values());
}
else
{
plugin.getCloudExpansionManager().findCloudExpansionByName(params.get(0)).ifPresent(expansions::add);
} else {
plugin.getCloudExpansionManager().findCloudExpansionByName(params.get(0))
.ifPresent(expansions::add);
}
// remove the ones that are the latest version
expansions.removeIf(expansion -> !expansion.shouldUpdate());
if (expansions.isEmpty())
{
if (expansions.isEmpty()) {
Msg.msg(sender,
"&cNo updates available for " + (!multiple ? "this expansion." : "your active expansions."));
"&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")));
"&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)
{
if (exception != null) {
Msg.msg(sender,
"&cFailed to update expansions: &e" + exception.getMessage());
return;
@ -99,7 +101,6 @@ public final class CommandECloudUpdate extends PlaceholderCommand
Msg.msg(sender,
"&aSuccessfully downloaded updates, registering new versions.");
final String message = classes.stream()
.filter(Objects::nonNull)
.map(plugin.getLocalExpansionManager()::register)
@ -115,31 +116,25 @@ public final class CommandECloudUpdate extends PlaceholderCommand
}
@Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions)
{
if (params.size() > 1)
{
public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 1) {
return;
}
final List<CloudExpansion> installed = Lists.newArrayList(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values());
final List<CloudExpansion> installed = Lists
.newArrayList(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values());
installed.removeIf(expansion -> !expansion.shouldUpdate());
if (!installed.isEmpty() && (params.isEmpty() || "all".startsWith(params.get(0).toLowerCase())))
{
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<List<@Nullable Class<? extends PlaceholderExpansion>>> downloadAndDiscover(@NotNull final List<CloudExpansion> 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));
}
}

View File

@ -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,30 +41,37 @@ 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
{
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)
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.US)
.withZone(ZoneId.of("UTC"));
public CommandDump()
{
public CommandDump() {
super("dump");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
postDump(makeDump(plugin)).whenComplete((key, exception) -> {
if (exception != null)
{
if (exception != null) {
plugin.getLogger().log(Level.WARNING, "failed to post dump details", exception);
Msg.msg(sender,
@ -87,40 +85,35 @@ public final class CommandDump extends PlaceholderCommand
}
@NotNull
private CompletableFuture<String> postDump(@NotNull final String dump)
{
private CompletableFuture<String> postDump(@NotNull final String dump) {
return CompletableFuture.supplyAsync(() -> {
try
{
final HttpURLConnection connection = ((HttpURLConnection) new URL(URL + "documents").openConnection());
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())
{
try (final OutputStream stream = connection.getOutputStream()) {
stream.write(dump.getBytes(StandardCharsets.UTF_8));
}
try (final InputStream stream = connection.getInputStream())
{
try (final InputStream stream = connection.getInputStream()) {
//noinspection UnstableApiUsage
final String json = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8));
final String json = CharStreams
.toString(new InputStreamReader(stream, StandardCharsets.UTF_8));
return JsonParser.parseString(json).getAsJsonObject().get("key").getAsString();
}
}
catch (final IOException ex)
{
} catch (final IOException ex) {
throw new CompletionException(ex);
}
});
}
@NotNull
private String makeDump(@NotNull final PlaceholderAPIPlugin plugin)
{
private String makeDump(@NotNull final PlaceholderAPIPlugin plugin) {
final StringBuilder builder = new StringBuilder();
builder.append("Generated: ")
@ -143,7 +136,8 @@ public final class CommandDump extends PlaceholderCommand
int size = 0;
for(final String name : expansions.stream().map(PlaceholderExpansion::getIdentifier).collect(Collectors.toList())){
for (final String name : expansions.stream().map(PlaceholderExpansion::getIdentifier)
.collect(Collectors.toList())) {
if (name.length() > size) {
size = name.length();
}
@ -169,8 +163,7 @@ public final class CommandDump extends PlaceholderCommand
.getExpansionsFolder()
.list((dir, name) -> name.toLowerCase().endsWith(".jar"));
for (final String jar : jars)
{
for (final String jar : jars) {
builder.append(" ")
.append(jar)
.append('\n');
@ -178,7 +171,6 @@ public final class CommandDump extends PlaceholderCommand
builder.append('\n');
builder.append("Server Info: ")
.append(plugin.getServer().getBukkitVersion())
.append('/')
@ -192,14 +184,14 @@ public final class CommandDump extends PlaceholderCommand
.sorted(Comparator.comparing(Plugin::getName))
.collect(Collectors.toList());
for (final String pluginName : plugins.stream().map(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)
{
for (final Plugin other : plugins) {
builder.append(" ")
.append(String.format("%-" + size + "s", other.getName()))
.append(" [Version: ")

View File

@ -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,62 +35,49 @@ 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()
{
public CommandExpansionRegister() {
super("register");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
if (params.size() < 1)
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> 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())
{
if (!file.exists()) {
Msg.msg(sender,
"&cThe file &f" + file.getName() + "&c doesn't exist!");
return;
}
Futures.onMainThread(plugin, manager.findExpansionInFile(file), (clazz, exception) -> {
if (exception != null)
{
if (exception != null) {
Msg.msg(sender,
"&cFailed to find expansion in file: &f" + file);
plugin.getLogger().log(Level.WARNING, "failed to find expansion in file: " + file, exception);
plugin.getLogger()
.log(Level.WARNING, "failed to find expansion in file: " + file, exception);
return;
}
if (clazz == null)
{
if (clazz == null) {
Msg.msg(sender,
"&cNo expansion class found in file: &f" + file);
return;
}
final Optional<PlaceholderExpansion> expansion = manager.register(clazz);
if (!expansion.isPresent())
{
if (!expansion.isPresent()) {
Msg.msg(sender,
"&cFailed to register expansion from &f" + params.get(0));
return;
@ -98,20 +90,21 @@ public final class CommandExpansionRegister extends PlaceholderCommand
}
@Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions)
{
if (params.size() > 1)
{
public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() > 1) {
return;
}
final String[] fileNames = plugin.getLocalExpansionManager().getExpansionsFolder().list((dir, name) -> name.endsWith(".jar"));
if (fileNames == null || fileNames.length == 0)
{
final String[] fileNames = plugin.getLocalExpansionManager().getExpansionsFolder()
.list((dir, name) -> name.endsWith(".jar"));
if (fileNames == null || fileNames.length == 0) {
return;
}
suggestByParameter(Arrays.stream(fileNames), suggestions, params.isEmpty() ? null : params.get(0));
suggestByParameter(Arrays.stream(fileNames), suggestions,
params.isEmpty() ? null : params.get(0));
}
}

View File

@ -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,36 +31,30 @@ 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()
{
public CommandExpansionUnregister() {
super("unregister");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
if (params.isEmpty())
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
if (params.isEmpty()) {
Msg.msg(sender,
"&cYou must specify the name of the expansion.");
return;
}
final Optional<PlaceholderExpansion> expansion = plugin.getLocalExpansionManager().findExpansionByName(params.get(0));
if (!expansion.isPresent())
{
final Optional<PlaceholderExpansion> 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";
@ -67,14 +63,15 @@ public final class CommandExpansionUnregister extends PlaceholderCommand
}
@Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions)
{
if (params.size() > 1)
{
public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> 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));
}
}

View File

@ -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,20 +29,17 @@ 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()
{
public CommandHelp() {
super("help");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
final PluginDescriptionFile description = plugin.getDescription();
Msg.msg(sender,

View File

@ -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,29 +30,25 @@ 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()
{
public CommandInfo() {
super("info");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
if (params.isEmpty())
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> 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)
{
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;
@ -67,37 +64,32 @@ public final class CommandInfo extends PlaceholderCommand
.append('\n');
final String author = expansion.getAuthor();
if (author != null)
{
if (author != null) {
builder.append("&7Author: &r")
.append(author)
.append('\n');
}
final String version = expansion.getVersion();
if (version != null)
{
if (version != null) {
builder.append("&7Version: &r")
.append(version)
.append('\n');
}
final String requiredPlugin = expansion.getRequiredPlugin();
if (requiredPlugin != null)
{
if (requiredPlugin != null) {
builder.append("&7Requires plugin: &r")
.append(requiredPlugin)
.append('\n');
}
final List<String> placeholders = expansion.getPlaceholders();
if (placeholders != null && !placeholders.isEmpty())
{
if (placeholders != null && !placeholders.isEmpty()) {
builder.append("&8&m-- &7Placeholders &8&m--&r")
.append('\n');
for (final String placeholder : placeholders)
{
for (final String placeholder : placeholders) {
builder.append(placeholder)
.append('\n');
}
@ -107,14 +99,15 @@ public final class CommandInfo extends PlaceholderCommand
}
@Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions)
{
if (params.size() > 1)
{
public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> 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));
}
}

View File

@ -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()
{
public CommandList() {
super("list");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
final Set<String> identifiers = PlaceholderAPI.getRegisteredIdentifiers();
if (identifiers.isEmpty())
{
if (identifiers.isEmpty()) {
Msg.msg(sender, "&cThere are no placeholder hooks active!");
return;
}
final List<List<String>> partitions = Lists.partition(identifiers.stream().sorted().collect(Collectors.toList()), 10);
final List<List<String>> 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")));
partitions.stream().map(partition -> String.join("&7, &a", partition))
.collect(Collectors.joining("\n")));
}
}

View File

@ -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,27 +38,18 @@ 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()
{
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<String> params)
{
switch (alias.toLowerCase())
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
switch (alias.toLowerCase()) {
case "parserel":
evaluateParseRelation(sender, params);
break;
@ -71,10 +66,10 @@ public final class CommandParse extends PlaceholderCommand
}
@Override
public void complete(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions)
{
switch (alias.toLowerCase())
{
public void complete(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
switch (alias.toLowerCase()) {
case "parserel":
completeParseRelation(params, suggestions);
break;
@ -87,31 +82,28 @@ public final class CommandParse extends PlaceholderCommand
}
private void evaluateParseSingular(@NotNull final CommandSender sender, @NotNull @Unmodifiable final List<String> 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}");
private void evaluateParseSingular(@NotNull final CommandSender sender,
@NotNull @Unmodifiable final List<String> 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;
if ("me".equalsIgnoreCase(params.get(0)))
{
if (!(sender instanceof Player))
{
if ("me".equalsIgnoreCase(params.get(0))) {
if (!(sender instanceof Player)) {
Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!");
return;
}
player = ((Player) sender);
}
else
{
} else {
final OfflinePlayer target = resolvePlayer(params.get(0));
if (target == null)
{
if (target == null) {
Msg.msg(sender, "&cFailed to find player: &7" + params.get(0));
return;
}
@ -119,64 +111,57 @@ public final class CommandParse extends PlaceholderCommand
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)
{
if (command) {
Bukkit.dispatchCommand(sender, message);
return;
}
if (broadcast)
{
if (broadcast) {
Msg.broadcast(message);
}
else
{
if (!(sender instanceof Player))
{
} else {
if (!(sender instanceof Player)) {
Msg.msg(sender, message);
}
else
{
} else {
((Player) sender).spigot().sendMessage(TextComponent.fromLegacyText(message));
}
}
}
private void evaluateParseRelation(@NotNull final CommandSender sender, @NotNull @Unmodifiable final List<String> 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}");
private void evaluateParseRelation(@NotNull final CommandSender sender,
@NotNull @Unmodifiable final List<String> 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())
{
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())
{
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())));
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<String> params, @NotNull final List<String> suggestions)
{
if (params.size() <= 1)
{
if (sender instanceof Player && (params.isEmpty() || "me".startsWith(params.get(0).toLowerCase())))
{
private void completeParseSingular(@NotNull final CommandSender sender,
@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions) {
if (params.size() <= 1) {
if (sender instanceof Player && (params.isEmpty() || "me"
.startsWith(params.get(0).toLowerCase()))) {
suggestions.add("me");
}
@ -187,20 +172,19 @@ public final class CommandParse extends PlaceholderCommand
}
final String name = params.get(params.size() - 1);
if (!name.startsWith("%") || name.endsWith("%"))
{
if (!name.startsWith("%") || name.endsWith("%")) {
return;
}
final int index = name.indexOf('_');
if (index == -1)
{
if (index == -1) {
return; // no arguments supplied yet
}
final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance().getLocalExpansionManager().findExpansionByIdentifier(name.substring(1, index)).orElse(null);
if (expansion == null)
{
final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance()
.getLocalExpansionManager().findExpansionByIdentifier(name.substring(1, index))
.orElse(null);
if (expansion == null) {
return;
}
@ -214,10 +198,9 @@ public final class CommandParse extends PlaceholderCommand
suggestByParameter(possible.stream(), suggestions, params.get(params.size() - 1));
}
private void completeParseRelation(@NotNull @Unmodifiable final List<String> params, @NotNull final List<String> suggestions)
{
if (params.size() > 2)
{
private void completeParseRelation(@NotNull @Unmodifiable final List<String> params,
@NotNull final List<String> suggestions) {
if (params.size() > 2) {
return;
}
@ -227,12 +210,10 @@ public final class CommandParse extends PlaceholderCommand
@Nullable
private OfflinePlayer resolvePlayer(@NotNull final String name)
{
private OfflinePlayer resolvePlayer(@NotNull final String name) {
OfflinePlayer target = Bukkit.getPlayer(name);
if (target == null)
{
if (target == null) {
target = Bukkit.getOfflinePlayer(name); // this is probably not a great idea.
}

View File

@ -20,25 +20,23 @@
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()
{
public CommandReload() {
super("reload");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
plugin.reloadConf(sender);
}

View File

@ -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,20 +29,17 @@ 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()
{
public CommandVersion() {
super("version");
}
@Override
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, @NotNull final CommandSender sender, @NotNull final String alias, @NotNull @Unmodifiable final List<String> params)
{
public void evaluate(@NotNull final PlaceholderAPIPlugin plugin,
@NotNull final CommandSender sender, @NotNull final String alias,
@NotNull @Unmodifiable final List<String> params) {
final PluginDescriptionFile description = plugin.getDescription();
Msg.msg(sender,

View File

@ -20,13 +20,11 @@
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<CloudExpansion>
{
public enum ExpansionSort implements Comparator<CloudExpansion> {
NAME(Comparator.comparing(CloudExpansion::getName)),
AUTHOR(Comparator.comparing(CloudExpansion::getAuthor)),
@ -36,15 +34,13 @@ public enum ExpansionSort implements Comparator<CloudExpansion>
@NotNull
private final Comparator<CloudExpansion> comparator;
ExpansionSort(@NotNull final Comparator<CloudExpansion> comparator)
{
ExpansionSort(@NotNull final Comparator<CloudExpansion> comparator) {
this.comparator = comparator;
}
@Override
public final int compare(final CloudExpansion expansion1, final CloudExpansion expansion2)
{
public final int compare(final CloudExpansion expansion1, final CloudExpansion expansion2) {
return comparator.compare(expansion1, expansion2);
}

View File

@ -20,86 +20,72 @@
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;
public PlaceholderAPIConfig(@NotNull final PlaceholderAPIPlugin plugin)
{
public PlaceholderAPIConfig(@NotNull final PlaceholderAPIPlugin plugin) {
this.plugin = plugin;
}
public boolean checkUpdates()
{
public boolean checkUpdates() {
return plugin.getConfig().getBoolean("check_updates");
}
public boolean cloudAllowUnverifiedExpansions()
{
public boolean cloudAllowUnverifiedExpansions() {
return plugin.getConfig().getBoolean("cloud_allow_unverified_expansions");
}
public boolean isCloudEnabled()
{
public boolean isCloudEnabled() {
return plugin.getConfig().getBoolean("cloud_enabled");
}
public void setCloudEnabled(boolean state)
{
public void setCloudEnabled(boolean state) {
plugin.getConfig().set("cloud_enabled", state);
plugin.saveConfig();
}
public boolean isDebugMode()
{
public boolean isDebugMode() {
return plugin.getConfig().getBoolean("debug", false);
}
public Optional<ExpansionSort> getExpansionSort()
{
final String option = plugin.getConfig().getString("cloud_sorting", ExpansionSort.LATEST.name());
public Optional<ExpansionSort> getExpansionSort() {
final String option = plugin.getConfig()
.getString("cloud_sorting", ExpansionSort.LATEST.name());
try
{
try {
//noinspection ConstantConditions (bad spigot annotation)
return Optional.of(ExpansionSort.valueOf(option.toUpperCase()));
}
catch (final IllegalArgumentException ignored)
{
} catch (final IllegalArgumentException ignored) {
return Optional.empty();
}
}
@NotNull
public String dateFormat()
{
public String dateFormat() {
//noinspection ConstantConditions (bad spigot annotation)
return plugin.getConfig().getString("date_format", "MM/dd/yy HH:mm:ss");
}
@NotNull
public String booleanTrue()
{
public String booleanTrue() {
//noinspection ConstantConditions (bad spigot annotation)
return plugin.getConfig().getString("boolean.true", "true");
}
@NotNull
public String booleanFalse()
{
public String booleanFalse() {
//noinspection ConstantConditions (bad spigot annotation)
return plugin.getConfig().getString("boolean.false", "false");
}

View File

@ -26,54 +26,41 @@ 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();
private boolean cancelled;
@NotNull
private final PlaceholderExpansion expansion;
private boolean cancelled;
public ExpansionRegisterEvent(@NotNull final PlaceholderExpansion expansion)
{
public ExpansionRegisterEvent(@NotNull final PlaceholderExpansion expansion) {
this.expansion = expansion;
}
@NotNull
public static HandlerList getHandlerList() {
return HANDLERS;
}
@NotNull
public PlaceholderExpansion getExpansion()
{
public PlaceholderExpansion getExpansion() {
return expansion;
}
@Override
public boolean isCancelled()
{
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancelled)
{
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@NotNull
@Override
public HandlerList getHandlers()
{
return HANDLERS;
}
@NotNull
public static HandlerList getHandlerList()
{
public HandlerList getHandlers() {
return HANDLERS;
}

View File

@ -25,8 +25,7 @@ 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();
@ -35,30 +34,23 @@ public final class ExpansionUnregisterEvent extends Event
@NotNull
private final PlaceholderExpansion expansion;
public ExpansionUnregisterEvent(@NotNull final PlaceholderExpansion expansion)
{
public ExpansionUnregisterEvent(@NotNull final PlaceholderExpansion expansion) {
this.expansion = expansion;
}
@NotNull
public static HandlerList getHandlerList() {
return HANDLERS;
}
@NotNull
public PlaceholderExpansion getExpansion()
{
public PlaceholderExpansion getExpansion() {
return expansion;
}
@NotNull
@Override
public HandlerList getHandlers()
{
return HANDLERS;
}
@NotNull
public static HandlerList getHandlerList()
{
public HandlerList getHandlers() {
return HANDLERS;
}

View File

@ -29,8 +29,7 @@ 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();
@ -41,36 +40,30 @@ public final class PlaceholderHookUnloadEvent extends Event
@NotNull
private final PlaceholderHook placeholderHook;
public PlaceholderHookUnloadEvent(@NotNull final String plugin, @NotNull final PlaceholderHook placeholderHook)
{
public PlaceholderHookUnloadEvent(@NotNull final String plugin,
@NotNull final PlaceholderHook placeholderHook) {
this.plugin = plugin;
this.placeholderHook = placeholderHook;
}
@NotNull
public String getHookName()
{
public static HandlerList getHandlerList() {
return HANDLERS;
}
@NotNull
public String getHookName() {
return plugin;
}
@NotNull
public PlaceholderHook getHook()
{
public PlaceholderHook getHook() {
return placeholderHook;
}
@NotNull
@Override
public HandlerList getHandlers()
{
return HANDLERS;
}
@NotNull
public static HandlerList getHandlerList()
{
public HandlerList getHandlers() {
return HANDLERS;
}

View File

@ -21,6 +21,7 @@
package me.clip.placeholderapi.exceptions;
public final class NoDefaultCommandException extends RuntimeException {
public NoDefaultCommandException(final String message) {
super(message);
}

View File

@ -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,12 +33,7 @@ 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
@ -63,8 +61,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
@Nullable
@Override /* override for now >:) */
public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params)
{
public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params) {
return super.onRequest(player, params);
}
@ -75,8 +72,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
* @return {@link #getIdentifier()} by default, name of this expansion if specified
*/
@NotNull
public String getName()
{
public String getName() {
return getIdentifier();
}
@ -86,8 +82,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
* @return plugin name that this expansion requires to function
*/
@Nullable
public String getRequiredPlugin()
{
public String getRequiredPlugin() {
return getPlugin();
}
@ -97,8 +92,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
* @return placeholder list that this expansion provides
*/
@NotNull
public List<String> getPlaceholders()
{
public List<String> getPlaceholders() {
return Collections.emptyList();
}
@ -110,8 +104,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
*
* @return if this expansion should persist through placeholder reloads
*/
public boolean persist()
{
public boolean persist() {
return false;
}
@ -121,9 +114,9 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
*
* @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);
public final boolean isRegistered() {
return getPlaceholderAPI().getLocalExpansionManager().findExpansionByIdentifier(getIdentifier())
.map(it -> it.equals(this)).orElse(false);
}
@ -133,9 +126,9 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
*
* @return true if this hook meets all the requirements to register
*/
public boolean canRegister()
{
return getRequiredPlugin() == null || Bukkit.getPluginManager().getPlugin(getRequiredPlugin()) != null;
public boolean canRegister() {
return getRequiredPlugin() == null
|| Bukkit.getPluginManager().getPlugin(getRequiredPlugin()) != null;
}
/**
@ -143,8 +136,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
*
* @return true if this expansion is now registered with PlaceholderAPI
*/
public boolean register()
{
public boolean register() {
return canRegister() && getPlaceholderAPI().getLocalExpansionManager().register(this);
}
@ -153,8 +145,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
*
* @return true if this expansion is now unregistered with PlaceholderAPI
*/
public final boolean unregister()
{
public final boolean unregister() {
return getPlaceholderAPI().getLocalExpansionManager().unregister(this);
}
@ -165,83 +156,69 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
* @return {@link PlaceholderAPIPlugin} instance
*/
@NotNull
public final PlaceholderAPIPlugin getPlaceholderAPI()
{
public final PlaceholderAPIPlugin getPlaceholderAPI() {
return PlaceholderAPIPlugin.getInstance();
}
// === Configuration ===
@Nullable
public final ConfigurationSection getConfigSection()
{
public final ConfigurationSection getConfigSection() {
return getPlaceholderAPI().getConfig().getConfigurationSection("expansions." + getIdentifier());
}
@Nullable
public final ConfigurationSection getConfigSection(@NotNull final String path)
{
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)
{
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)
{
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)
{
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)
{
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)
{
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<String> getStringList(@NotNull final String path)
{
public final List<String> 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)
{
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)
{
public final boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PlaceholderExpansion))
{
if (!(o instanceof PlaceholderExpansion)) {
return false;
}
@ -253,15 +230,14 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
}
@Override
public final int hashCode()
{
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());
public final String toString() {
return String.format("PlaceholderExpansion[name: '%s', author: '%s', version: '%s']", getName(),
getAuthor(), getVersion());
}
// === Deprecated API ===
@ -271,8 +247,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2.11.0")
public String getPlugin()
{
public String getPlugin() {
return null;
}
@ -281,8 +256,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2.11.0")
public String getDescription()
{
public String getDescription() {
return null;
}
@ -291,8 +265,7 @@ public abstract class PlaceholderExpansion extends PlaceholderHook
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2.11.0")
public String getLink()
{
public String getLink() {
return null;
}

View File

@ -20,11 +20,10 @@
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 {
@ -173,6 +172,7 @@ public class CloudExpansion {
}
public class Version {
private String url, version, release_notes;
public String getUrl() {

View File

@ -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,9 +44,13 @@ 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/";
@ -59,7 +61,8 @@ public final class CloudExpansionManager
private static final Type TYPE = new TypeToken<Map<String, CloudExpansion>>() {}.getType();
@NotNull
private final Collector<CloudExpansion, ?, Map<String, CloudExpansion>> INDEXED_NAME_COLLECTOR = Collectors.toMap(CloudExpansionManager::toIndexName, Function.identity());
private final Collector<CloudExpansion, ?, Map<String, CloudExpansion>> INDEXED_NAME_COLLECTOR = Collectors
.toMap(CloudExpansionManager::toIndexName, Function.identity());
@NotNull
@ -71,37 +74,39 @@ public final class CloudExpansionManager
private final Map<String, CompletableFuture<File>> await = new ConcurrentHashMap<>();
public CloudExpansionManager(@NotNull final PlaceholderAPIPlugin 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()
{
@NotNull
private static String toIndexName(@NotNull final CloudExpansion expansion) {
return toIndexName(expansion.getName());
}
public void load() {
clean();
fetch(plugin.getPlaceholderAPIConfig().cloudAllowUnverifiedExpansions());
}
public void kill()
{
public void kill() {
clean();
}
@NotNull
@Unmodifiable
public Map<String, CloudExpansion> getCloudExpansions()
{
public Map<String, CloudExpansion> getCloudExpansions() {
return ImmutableMap.copyOf(cache);
}
@NotNull
@Unmodifiable
public Map<String, CloudExpansion> getCloudExpansionsInstalled()
{
if (cache.isEmpty())
{
public Map<String, CloudExpansion> getCloudExpansionsInstalled() {
if (cache.isEmpty()) {
return Collections.emptyMap();
}
@ -113,10 +118,8 @@ public final class CloudExpansionManager
@NotNull
@Unmodifiable
public Map<String, CloudExpansion> getCloudExpansionsByAuthor(@NotNull final String author)
{
if (cache.isEmpty())
{
public Map<String, CloudExpansion> getCloudExpansionsByAuthor(@NotNull final String author) {
if (cache.isEmpty()) {
return Collections.emptyMap();
}
@ -128,83 +131,70 @@ public final class CloudExpansionManager
@NotNull
@Unmodifiable
public Set<String> getCloudExpansionAuthors()
{
public Set<String> getCloudExpansionAuthors() {
return cache.values().stream().map(CloudExpansion::getAuthor).collect(Collectors.toSet());
}
public int getCloudExpansionAuthorCount()
{
public int getCloudExpansionAuthorCount() {
return getCloudExpansionAuthors().size();
}
public int getCloudUpdateCount()
{
public int getCloudUpdateCount() {
return ((int) plugin.getLocalExpansionManager()
.getExpansions()
.stream()
.filter(expansion -> findCloudExpansionByName(expansion.getName()).map(CloudExpansion::shouldUpdate).orElse(false))
.filter(expansion -> findCloudExpansionByName(expansion.getName())
.map(CloudExpansion::shouldUpdate).orElse(false))
.count());
}
@NotNull
public Optional<CloudExpansion> findCloudExpansionByName(@NotNull final String name)
{
public Optional<CloudExpansion> findCloudExpansionByName(@NotNull final String name) {
return Optional.ofNullable(cache.get(toIndexName(name)));
}
public void clean()
{
public void clean() {
cache.clear();
await.values().forEach(future -> future.cancel(true));
await.clear();
}
public void fetch(final boolean allowUnverified)
{
public void fetch(final boolean allowUnverified) {
plugin.getLogger().info("Fetching available expansion information...");
CompletableFuture<Map<String, CloudExpansion>> future = CompletableFuture.supplyAsync(() -> {
final Map<String, CloudExpansion> values = new HashMap<>();
try
{
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)
{
} catch (final IOException ex) {
throw new CompletionException(ex);
}
values.values().removeIf(value -> value.getLatestVersion() == null || value.getVersion(value.getLatestVersion()) == null);
values.values().removeIf(value -> value.getLatestVersion() == null
|| value.getVersion(value.getLatestVersion()) == null);
return values;
});
if (!allowUnverified)
{
if (!allowUnverified) {
future = future.thenApplyAsync((values) -> {
values.values().removeIf(expansion -> !expansion.isVerified());
return values;
});
}
future = future.thenApplyAsync((values) -> {
values.forEach((name, expansion) -> {
expansion.setName(name);
final Optional<PlaceholderExpansion> local = plugin.getLocalExpansionManager().findExpansionByName(name);
if (local.isPresent() && local.get().isRegistered())
{
final Optional<PlaceholderExpansion> local = plugin.getLocalExpansionManager()
.findExpansionByName(name);
if (local.isPresent() && local.get().isRegistered()) {
expansion.setHasExpansion(true);
expansion.setShouldUpdate(!local.get().getVersion().equals(expansion.getLatestVersion()));
}
@ -215,44 +205,38 @@ public final class CloudExpansionManager
future.whenComplete((expansions, exception) -> {
if (exception != null)
{
plugin.getLogger().log(Level.WARNING, "failed to download expansion information", exception);
if (exception != null) {
plugin.getLogger()
.log(Level.WARNING, "failed to download expansion information", exception);
return;
}
for (final CloudExpansion expansion : expansions.values())
{
for (final CloudExpansion expansion : expansions.values()) {
this.cache.put(toIndexName(expansion), expansion);
}
});
}
public boolean isDownloading(@NotNull final CloudExpansion expansion)
{
public boolean isDownloading(@NotNull final CloudExpansion expansion) {
return await.containsKey(toIndexName(expansion));
}
@NotNull
public CompletableFuture<File> downloadExpansion(@NotNull final CloudExpansion expansion, @NotNull final CloudExpansion.Version version)
{
public CompletableFuture<File> downloadExpansion(@NotNull final CloudExpansion expansion,
@NotNull final CloudExpansion.Version version) {
final CompletableFuture<File> previous = await.get(toIndexName(expansion));
if (previous != null)
{
if (previous != null) {
return previous;
}
final File file = new File(plugin.getLocalExpansionManager().getExpansionsFolder(), "Expansion-" + toIndexName(expansion) + ".jar");
final File file = new File(plugin.getLocalExpansionManager().getExpansionsFolder(),
"Expansion-" + toIndexName(expansion) + ".jar");
final CompletableFuture<File> download = CompletableFuture.supplyAsync(() -> {
try (final ReadableByteChannel source = Channels.newChannel(new URL(version.getUrl()).openStream()); final FileOutputStream target = new FileOutputStream(file))
{
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)
{
} catch (final IOException ex) {
throw new CompletionException(ex);
}
return file;
@ -261,9 +245,9 @@ public final class CloudExpansionManager
download.whenCompleteAsync((value, exception) -> {
await.remove(toIndexName(expansion));
if (exception != null)
{
plugin.getLogger().log(Level.SEVERE, "failed to download " + expansion.getName() + ":" + version.getVersion(), exception);
if (exception != null) {
plugin.getLogger().log(Level.SEVERE,
"failed to download " + expansion.getName() + ":" + version.getVersion(), exception);
}
});
@ -272,17 +256,4 @@ public final class CloudExpansionManager
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());
}
}

View File

@ -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,19 +59,7 @@ 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
{
public final class LocalExpansionManager implements Listener {
@NotNull
private static final String EXPANSIONS_FOLDER_NAME = "expansions";
@ -71,91 +74,79 @@ public final class LocalExpansionManager implements Listener
private final Map<String, PlaceholderExpansion> expansions = new HashMap<>();
public LocalExpansionManager(@NotNull final PlaceholderAPIPlugin plugin)
{
public LocalExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) {
this.plugin = plugin;
this.folder = new File(plugin.getDataFolder(), EXPANSIONS_FOLDER_NAME);
if (!this.folder.exists() && !folder.mkdirs())
{
if (!this.folder.exists() && !folder.mkdirs()) {
plugin.getLogger().log(Level.WARNING, "failed to create expansions folder!");
}
}
public void load(@NotNull final CommandSender sender)
{
public void load(@NotNull final CommandSender sender) {
registerAll(sender);
}
public void kill()
{
public void kill() {
unregisterAll();
}
@NotNull
public File getExpansionsFolder()
{
public File getExpansionsFolder() {
return folder;
}
public int getExpansionsCount()
{
public int getExpansionsCount() {
return expansions.size();
}
@NotNull
@Unmodifiable
public Collection<String> getIdentifiers()
{
public Collection<String> getIdentifiers() {
return ImmutableSet.copyOf(expansions.keySet());
}
@NotNull
@Unmodifiable
public Collection<PlaceholderExpansion> getExpansions()
{
public Collection<PlaceholderExpansion> getExpansions() {
return ImmutableSet.copyOf(expansions.values());
}
@Nullable
public PlaceholderExpansion getExpansion(@NotNull final String identifier)
{
public PlaceholderExpansion getExpansion(@NotNull final String identifier) {
return expansions.get(identifier.toLowerCase());
}
@NotNull
public Optional<PlaceholderExpansion> findExpansionByName(@NotNull final String name)
{
return expansions.values().stream().filter(expansion -> name.equalsIgnoreCase(expansion.getName())).findFirst();
public Optional<PlaceholderExpansion> findExpansionByName(@NotNull final String name) {
return expansions.values().stream()
.filter(expansion -> name.equalsIgnoreCase(expansion.getName())).findFirst();
}
@NotNull
public Optional<PlaceholderExpansion> findExpansionByIdentifier(@NotNull final String identifier)
{
public Optional<PlaceholderExpansion> findExpansionByIdentifier(
@NotNull final String identifier) {
return Optional.ofNullable(getExpansion(identifier));
}
public Optional<PlaceholderExpansion> register(@NotNull final Class<? extends PlaceholderExpansion> clazz)
{
try
{
public Optional<PlaceholderExpansion> register(
@NotNull final Class<? extends PlaceholderExpansion> clazz) {
try {
final PlaceholderExpansion expansion = createExpansionInstance(clazz);
if (expansion == null || !expansion.register())
{
if (expansion == null || !expansion.register()) {
return Optional.empty();
}
return Optional.of(expansion);
}
catch (final LinkageError ex)
{
} 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());
"Failed to load due to a [" + ex.getClass().getSimpleName() + "], attempted to use " + ex
.getMessage());
}
return Optional.empty();
@ -165,38 +156,28 @@ public final class LocalExpansionManager implements Listener
* Do not call this method yourself, use {@link PlaceholderExpansion#register()}
*/
@ApiStatus.Internal
public boolean register(@NotNull final PlaceholderExpansion expansion)
{
public boolean register(@NotNull final PlaceholderExpansion expansion) {
final String identifier = expansion.getIdentifier().toLowerCase();
if (expansion instanceof Configurable)
{
if (expansion instanceof Configurable) {
Map<String, Object> defaults = ((Configurable) expansion).getDefaults();
String pre = "expansions." + identifier + ".";
FileConfiguration cfg = plugin.getConfig();
boolean save = false;
if (defaults != null)
{
for (Map.Entry<String, Object> entries : defaults.entrySet())
{
if (entries.getKey() == null || entries.getKey().isEmpty())
{
if (defaults != null) {
for (Map.Entry<String, Object> entries : defaults.entrySet()) {
if (entries.getKey() == null || entries.getKey().isEmpty()) {
continue;
}
if (entries.getValue() == null)
{
if (cfg.contains(pre + entries.getKey()))
{
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()))
{
} else {
if (!cfg.contains(pre + entries.getKey())) {
save = true;
cfg.set(pre + entries.getKey(), entries.getValue());
}
@ -204,58 +185,53 @@ public final class LocalExpansionManager implements Listener
}
}
if (save)
{
if (save) {
plugin.saveConfig();
plugin.reloadConfig();
}
}
if (expansion instanceof VersionSpecific)
{
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());
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())
{
if (removed != null && !removed.unregister()) {
return false;
}
final ExpansionRegisterEvent event = new ExpansionRegisterEvent(expansion);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled())
{
if (event.isCancelled()) {
return false;
}
expansions.put(identifier, expansion);
if (expansion instanceof Listener)
{
if (expansion instanceof Listener) {
Bukkit.getPluginManager().registerEvents(((Listener) expansion), plugin);
}
plugin.getLogger().info("Successfully registered expansion: " + expansion.getIdentifier());
if (expansion instanceof Taskable)
{
if (expansion instanceof Taskable) {
((Taskable) expansion).start();
}
if (plugin.getPlaceholderAPIConfig().isCloudEnabled())
{
final Optional<CloudExpansion> cloudExpansion = plugin.getCloudExpansionManager().findCloudExpansionByName(identifier);
if (cloudExpansion.isPresent())
{
if (plugin.getPlaceholderAPIConfig().isCloudEnabled()) {
final Optional<CloudExpansion> cloudExpansion = plugin.getCloudExpansionManager()
.findCloudExpansionByName(identifier);
if (cloudExpansion.isPresent()) {
cloudExpansion.get().setHasExpansion(true);
cloudExpansion.get().setShouldUpdate(!cloudExpansion.get().getLatestVersion().equals(expansion.getVersion()));
cloudExpansion.get().setShouldUpdate(
!cloudExpansion.get().getLatestVersion().equals(expansion.getVersion()));
}
}
@ -266,35 +242,28 @@ public final class LocalExpansionManager implements Listener
* 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)
{
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)
{
if (expansion instanceof Listener) {
HandlerList.unregisterAll((Listener) expansion);
}
if (expansion instanceof Taskable)
{
if (expansion instanceof Taskable) {
((Taskable) expansion).stop();
}
if (expansion instanceof Cacheable)
{
if (expansion instanceof Cacheable) {
((Cacheable) expansion).clear();
}
if (plugin.getPlaceholderAPIConfig().isCloudEnabled())
{
plugin.getCloudExpansionManager().findCloudExpansionByName(expansion.getName()).ifPresent(cloud -> {
if (plugin.getPlaceholderAPIConfig().isCloudEnabled()) {
plugin.getCloudExpansionManager().findCloudExpansionByName(expansion.getName())
.ifPresent(cloud -> {
cloud.setHasExpansion(false);
cloud.setShouldUpdate(false);
});
@ -304,30 +273,27 @@ public final class LocalExpansionManager implements Listener
}
private void registerAll(@NotNull final CommandSender sender)
{
private void registerAll(@NotNull final CommandSender sender) {
plugin.getLogger().info("Placeholder expansion registration initializing...");
Futures.onMainThread(plugin, findExpansionsOnDisk(), (classes, exception) -> {
if (exception != null)
{
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();
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!");
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())
{
private void unregisterAll() {
for (final PlaceholderExpansion expansion : Sets.newHashSet(expansions.values())) {
if (expansion.persist()) {
continue;
}
@ -337,29 +303,24 @@ public final class LocalExpansionManager implements Listener
@NotNull
public CompletableFuture<@NotNull List<@NotNull Class<? extends PlaceholderExpansion>>> findExpansionsOnDisk()
{
public CompletableFuture<@NotNull List<@NotNull Class<? extends PlaceholderExpansion>>> findExpansionsOnDisk() {
return Arrays.stream(folder.listFiles((dir, name) -> name.endsWith(".jar")))
.map(this::findExpansionInFile)
.collect(Futures.collector());
}
@NotNull
public CompletableFuture<@Nullable Class<? extends PlaceholderExpansion>> findExpansionInFile(@NotNull final File file)
{
public CompletableFuture<@Nullable Class<? extends PlaceholderExpansion>> findExpansionInFile(
@NotNull final File file) {
return CompletableFuture.supplyAsync(() -> {
try
{
try {
return FileUtil.findClass(file, PlaceholderExpansion.class);
}
catch (final VerifyError ex)
{
} 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(' ')));
"Failed to load due to a [" + ex.getClass().getSimpleName() + "], attempted to use" + ex
.getMessage().substring(ex.getMessage().lastIndexOf(' ')));
return null;
}
catch (final Exception ex)
{
} catch (final Exception ex) {
throw new CompletionException(ex);
}
});
@ -367,32 +328,27 @@ public final class LocalExpansionManager implements Listener
@Nullable
public PlaceholderExpansion createExpansionInstance(@NotNull final Class<? extends PlaceholderExpansion> clazz) throws LinkageError
{
try
{
public PlaceholderExpansion createExpansionInstance(
@NotNull final Class<? extends PlaceholderExpansion> clazz) throws LinkageError {
try {
return clazz.getDeclaredConstructor().newInstance();
}
catch (final Exception ex)
{
if (ex.getCause() instanceof LinkageError)
{
} 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);
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))
{
public void onQuit(@NotNull final PlayerQuitEvent event) {
for (final PlaceholderExpansion expansion : getExpansions()) {
if (!(expansion instanceof Cleanable)) {
continue;
}
@ -401,18 +357,14 @@ public final class LocalExpansionManager implements Listener
}
@EventHandler(priority = EventPriority.HIGH)
public void onPluginDisable(@NotNull final PluginDisableEvent event)
{
public void onPluginDisable(@NotNull final PluginDisableEvent event) {
final String name = event.getPlugin().getName();
if (name.equals(plugin.getName()))
{
if (name.equals(plugin.getName())) {
return;
}
for (final PlaceholderExpansion expansion : getExpansions())
{
if (!name.equalsIgnoreCase(expansion.getRequiredPlugin()))
{
for (final PlaceholderExpansion expansion : getExpansions()) {
if (!name.equalsIgnoreCase(expansion.getRequiredPlugin())) {
continue;
}

View File

@ -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<ChatColor, String> 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 &amp;6, &amp;l, &amp;4, etc.)
* Converts this {@link JSONMessage} object to the legacy formatting system, which uses formatting
* codes (like &amp;6, &amp;l, &amp;4, etc.)
*
* @return This {@link JSONMessage} instance {@link JSONMessage} in legacy format
*/
@ -190,12 +190,14 @@ public class JSONMessage {
* @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.
* <br>If the provided color is a hex color ({@code #rrggbb}) but the major version of MC is older than 1.16 will this
* <br>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,7 +244,8 @@ public class JSONMessage {
/**
* Sets the color of the current message part.
* <br>If the provided color is a hex color ({@code #rrggbb}) but the major version of MC is older than 1.16 will the provided
* <br>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
@ -248,8 +253,9 @@ public class JSONMessage {
* @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.
* <br>When this is used on versions older than 1.15 will this default to {@link #suggestCommand(String) suggestCommand(String)}.
* <br>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.
* <br>When used on versions older than 1.15 will this {@link #suggestCommand(String) suggest the text} instead.
* <br>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 <code>null</code> if something went wrong converting the String to JSON data
* @return The object representing the text in JSON form, or <code>null</code> 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.
* <br>
* <br>
* <a href="http://minecraft.gamepedia.com/Commands#Raw_JSON_text">Reference</a>
@ -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
*/

View File

@ -28,14 +28,12 @@ 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;
public ServerLoadEventListener(@NotNull final PlaceholderAPIPlugin plugin)
{
public ServerLoadEventListener(@NotNull final PlaceholderAPIPlugin plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
@ -44,16 +42,15 @@ public final class ServerLoadEventListener implements Listener
/**
* This method will be called when the server is first loaded
* <p>
* The goal of the method is to register all the expansions as soon as possible
* especially before players can join
* The goal of the method is to register all the expansions as soon as possible especially before
* players can join
* <p>
* This will ensure no issues with expansions and hooks.
*
* @param event the server load event
*/
@EventHandler
public void onServerLoad(@NotNull final ServerLoadEvent event)
{
public void onServerLoad(@NotNull final ServerLoadEvent event) {
HandlerList.unregisterAll(this);
plugin.getLocalExpansionManager().load(Bukkit.getConsoleSender());
}

View File

@ -20,60 +20,53 @@
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;
public CharsReplacer(@NotNull final Closure closure)
{
public CharsReplacer(@NotNull final Closure closure) {
this.closure = closure;
}
@NotNull
@Override
public String apply(@NotNull final String text, @Nullable final OfflinePlayer player, @NotNull final Function<String, @Nullable PlaceholderExpansion> lookup)
{
public String apply(@NotNull final String text, @Nullable final OfflinePlayer player,
@NotNull final Function<String, @Nullable PlaceholderExpansion> lookup) {
final char[] chars = text.toCharArray();
final StringBuilder builder = new StringBuilder(text.length());
final StringBuilder identifier = new StringBuilder();
final StringBuilder parameters = new StringBuilder();
for (int i = 0; i < chars.length; i++)
{
for (int i = 0; i < chars.length; i++) {
final char l = chars[i];
if (l == '&' && ++i < chars.length)
{
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')
{
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
{
} else {
builder.append(ChatColor.COLOR_CHAR);
if (c != 'x')
{
if (c != 'x') {
builder.append(chars[i]);
continue;
}
if ((i > 1 && chars[i - 2] == '\\') /*allow escaping &x*/)
{
if ((i > 1 && chars[i - 2] == '\\') /*allow escaping &x*/) {
builder.setLength(builder.length() - 2);
builder.append('&').append(chars[i]);
continue;
@ -82,10 +75,8 @@ public final class CharsReplacer implements Replacer
builder.append(c);
int j = 0;
while (++j <= 6)
{
if (i + j >= chars.length)
{
while (++j <= 6) {
if (i + j >= chars.length) {
break;
}
@ -93,20 +84,16 @@ public final class CharsReplacer implements Replacer
builder.append(ChatColor.COLOR_CHAR).append(x);
}
if (j == 7)
{
if (j == 7) {
i += 6;
}
else
{
} else {
builder.setLength(builder.length() - (j * 2)); // undo &x parsing
}
}
continue;
}
if (l != closure.head || i + 1 >= chars.length)
{
if (l != closure.head || i + 1 >= chars.length) {
builder.append(l);
continue;
}
@ -114,32 +101,25 @@ public final class CharsReplacer implements Replacer
boolean identified = false;
boolean oopsitsbad = true;
while (++i < chars.length)
{
while (++i < chars.length) {
final char p = chars[i];
if (p == ' ' && !identified)
{
if (p == ' ' && !identified) {
break;
}
if (p == closure.tail)
{
if (p == closure.tail) {
oopsitsbad = false;
break;
}
if (p == '_' && !identified)
{
if (p == '_' && !identified) {
identified = true;
continue;
}
if (identified)
{
if (identified) {
parameters.append(p);
}
else
{
} else {
identifier.append(p);
}
}
@ -150,12 +130,10 @@ public final class CharsReplacer implements Replacer
identifier.setLength(0);
parameters.setLength(0);
if (oopsitsbad)
{
if (oopsitsbad) {
builder.append(closure.head).append(identifierString);
if (identified)
{
if (identified) {
builder.append('_').append(parametersString);
}
@ -164,12 +142,10 @@ public final class CharsReplacer implements Replacer
}
final PlaceholderExpansion placeholder = lookup.apply(identifierString);
if (placeholder == null)
{
if (placeholder == null) {
builder.append(closure.head).append(identifierString);
if (identified)
{
if (identified) {
builder.append('_');
}
@ -178,12 +154,10 @@ public final class CharsReplacer implements Replacer
}
final String replacement = placeholder.onRequest(player, parametersString);
if (replacement == null)
{
if (replacement == null) {
builder.append(closure.head).append(identifierString);
if (identified)
{
if (identified) {
builder.append('_');
}

View File

@ -20,48 +20,44 @@
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;
public RegexReplacer(@NotNull final Closure closure)
{
this.pattern = Pattern.compile(String.format("\\%s((?<identifier>[a-zA-Z0-9]+)_)(?<parameters>[^%s%s]+)\\%s", closure.head, closure.head, closure.tail, closure.tail));
public RegexReplacer(@NotNull final Closure closure) {
this.pattern = Pattern.compile(String
.format("\\%s((?<identifier>[a-zA-Z0-9]+)_)(?<parameters>[^%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<String, @Nullable PlaceholderExpansion> lookup)
{
public String apply(@NotNull final String text, @Nullable final OfflinePlayer player,
@NotNull final Function<String, @Nullable PlaceholderExpansion> lookup) {
final Matcher matcher = pattern.matcher(text);
if (!matcher.find())
{
if (!matcher.find()) {
return text;
}
final StringBuffer builder = new StringBuffer();
do
{
do {
final String identifier = matcher.group("identifier");
final String parameters = matcher.group("parameters");
final PlaceholderExpansion expansion = lookup.apply(identifier);
if (expansion == null)
{
if (expansion == null) {
continue;
}

View File

@ -20,30 +20,27 @@
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<String, @Nullable PlaceholderExpansion> lookup);
String apply(@NotNull final String text, @Nullable final OfflinePlayer player,
@NotNull final Function<String, @Nullable PlaceholderExpansion> lookup);
enum Closure
{
enum Closure {
BRACKET('{', '}'),
PERCENT('%', '%');
public final char head, tail;
Closure(final char head, final char tail)
{
Closure(final char head, final char tail) {
this.head = head;
this.tail = tail;
}

View File

@ -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,11 +32,6 @@ 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;

View File

@ -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,15 +28,15 @@ 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 <T> Class<? extends T> findClass(@NotNull final File file, @NotNull final Class<T> clazz) throws IOException, ClassNotFoundException
{
if (!file.exists())
{
public static <T> Class<? extends T> findClass(@NotNull final File file,
@NotNull final Class<T> clazz) throws IOException, ClassNotFoundException {
if (!file.exists()) {
return null;
}
@ -48,33 +45,27 @@ public class FileUtil
final List<String> matches = new ArrayList<>();
final List<Class<? extends T>> classes = new ArrayList<>();
try (final JarInputStream stream = new JarInputStream(jar.openStream()); final URLClassLoader loader = new URLClassLoader(new URL[]{jar}, clazz.getClassLoader()))
{
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)
{
while ((entry = stream.getNextJarEntry()) != null) {
final String name = entry.getName();
if (name == null || name.isEmpty() || !name.endsWith(".class"))
{
if (name == null || name.isEmpty() || !name.endsWith(".class")) {
continue;
}
matches.add(name.substring(0, name.lastIndexOf('.')).replace('/', '.'));
}
for (final String match : matches)
{
try
{
for (final String match : matches) {
try {
final Class<?> loaded = loader.loadClass(match);
if (clazz.isAssignableFrom(loaded))
{
if (clazz.isAssignableFrom(loaded)) {
classes.add(loaded.asSubclass(clazz));
}
} catch (final NoClassDefFoundError ignored) {
}
catch (final NoClassDefFoundError ignored)
{ }
}
}

View File

@ -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
{
private Format()
{}
public enum Align
{
LEFT, RIGHT
}
public final class Format {
private Format() {}
@NotNull
public static Optional<List<String>> tablify(@NotNull final Align align, @NotNull final List<List<String>> rows)
{
public static Optional<List<String>> tablify(@NotNull final Align align,
@NotNull final List<List<String>> 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))
.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)
{
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<int[]> findSpacing(@NotNull final List<List<String>> rows)
{
private static Optional<int[]> findSpacing(@NotNull final List<List<String>> 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
}
}

View File

@ -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,23 +27,22 @@ 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 <T> void onMainThread(@NotNull final Plugin plugin, @NotNull final CompletableFuture<T> future, @NotNull final BiConsumer<T, Throwable> consumer)
{
public static <T> void onMainThread(@NotNull final Plugin plugin,
@NotNull final CompletableFuture<T> future,
@NotNull final BiConsumer<T, Throwable> consumer) {
future.whenComplete((value, exception) -> {
if (Bukkit.isPrimaryThread())
{
if (Bukkit.isPrimaryThread()) {
consumer.accept(value, exception);
}
else
{
} else {
Bukkit.getScheduler().runTask(plugin, () -> consumer.accept(value, exception));
}
});
@ -55,28 +50,27 @@ public final class Futures
@NotNull
public static <T> Collector<CompletableFuture<T>, ?, CompletableFuture<List<T>>> collector()
{
public static <T> Collector<CompletableFuture<T>, ?, CompletableFuture<List<T>>> collector() {
return Collectors.collectingAndThen(Collectors.toList(), Futures::of);
}
@NotNull
public static <T> CompletableFuture<List<T>> of(@NotNull final Stream<CompletableFuture<T>> futures)
{
public static <T> CompletableFuture<List<T>> of(
@NotNull final Stream<CompletableFuture<T>> futures) {
return of(futures.collect(Collectors.toList()));
}
@NotNull
public static <T> CompletableFuture<List<T>> of(@NotNull final Collection<CompletableFuture<T>> futures)
{
public static <T> CompletableFuture<List<T>> of(
@NotNull final Collection<CompletableFuture<T>> futures) {
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenApplyAsync($ -> awaitCompletion(futures));
}
@NotNull
private static <T> List<T> awaitCompletion(@NotNull final Collection<CompletableFuture<T>> futures)
{
private static <T> List<T> awaitCompletion(
@NotNull final Collection<CompletableFuture<T>> futures) {
return futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
}

View File

@ -20,39 +20,33 @@
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)
{
public static void msg(@NotNull final CommandSender sender, @NotNull final String... messages) {
if (messages.length == 0) {
return;
}
sender.sendMessage(Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n")));
}
public static void broadcast(@NotNull final String... messages)
{
if (messages.length == 0)
{
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)
{
public static String color(@NotNull final String text) {
return ChatColor.translateAlternateColorCodes('&', text);
}

View File

@ -121,7 +121,8 @@ public class TimeUtil {
/**
* 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)
* @param duration {@link Duration} (eg, Duration.of(20, {@link ChronoUnit#SECONDS}) for 20
* seconds)
* @return formatted time
*/
public static String getTime(final Duration duration) {

View File

@ -29,8 +29,7 @@ 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%";
@ -44,8 +43,7 @@ public interface Values
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";
@ -55,36 +53,30 @@ public interface Values
@NotNull
@Override
public String getIdentifier()
{
public String getIdentifier() {
return "player";
}
@NotNull
@Override
public String getAuthor()
{
public String getAuthor() {
return "Sxtanna";
}
@NotNull
@Override
public String getVersion()
{
public String getVersion() {
return "1.0";
}
@Override
public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params)
{
public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params) {
final String[] parts = params.split("_");
if (parts.length == 0)
{
if (parts.length == 0) {
return null;
}
switch (parts[0])
{
switch (parts[0]) {
case "name":
return PLAYER_NAME;
case "x":

View File

@ -23,30 +23,25 @@ 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()
{
public void measureCharsReplacerSmallText() {
Values.CHARS_REPLACER.apply(Values.SMALL_TEXT, null, Values.PLACEHOLDERS::get);
}
@Benchmark
public void measureRegexReplacerSmallText()
{
public void measureRegexReplacerSmallText() {
Values.REGEX_REPLACER.apply(Values.SMALL_TEXT, null, Values.PLACEHOLDERS::get);
}
@Benchmark
public void measureCharsReplacerLargeText()
{
public void measureCharsReplacerLargeText() {
Values.CHARS_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get);
}
@Benchmark
public void measureRegexReplacerLargeText()
{
public void measureRegexReplacerLargeText() {
Values.REGEX_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get);
}

View File

@ -20,47 +20,51 @@
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;
public final class ReplacerUnitTester {
@Test
void testCharsReplacerProducesExpectedSingleValue()
{
assertEquals(PLAYER_NAME, Values.CHARS_REPLACER.apply("%player_name%", null, Values.PLACEHOLDERS::get));
void testCharsReplacerProducesExpectedSingleValue() {
assertEquals(PLAYER_NAME,
Values.CHARS_REPLACER.apply("%player_name%", null, Values.PLACEHOLDERS::get));
}
@Test
void testRegexReplacerProducesExpectedSingleValue()
{
assertEquals(PLAYER_NAME, Values.REGEX_REPLACER.apply("%player_name%", null, Values.PLACEHOLDERS::get));
void testRegexReplacerProducesExpectedSingleValue() {
assertEquals(PLAYER_NAME,
Values.REGEX_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));
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 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));
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 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);
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(resultChars, resultRegex);
@ -68,28 +72,28 @@ public final class ReplacerUnitTester
}
@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);
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(resultChars, resultRegex);
}
@Test
void testCharsReplacerIgnoresMalformed()
{
void testCharsReplacerIgnoresMalformed() {
final String text = "10% and %hello world 15%";
assertEquals(text, Values.CHARS_REPLACER.apply(text, null, Values.PLACEHOLDERS::get));
}
@Test
void testCharsReplacerHandlesEscapedHex()
{
void testCharsReplacerHandlesEscapedHex() {
final String text = "\\&xffffffThis should not change.";
assertEquals(text.substring(1), Values.CHARS_REPLACER.apply(text, null, Values.PLACEHOLDERS::get));
assertEquals(text.substring(1),
Values.CHARS_REPLACER.apply(text, null, Values.PLACEHOLDERS::get));
}
}