Merge branch 'master' into gradle

# Conflicts:
#	pom.xml
This commit is contained in:
Sxtanna 2020-07-20 20:07:38 -04:00
commit 47e336c1fe
11 changed files with 1436 additions and 773 deletions

File diff suppressed because it is too large Load Diff

View File

@ -22,33 +22,43 @@ package me.clip.placeholderapi;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class PlaceholderHook { public abstract class PlaceholderHook
{
/** /**
* called when a placeholder value is requested from this hook * called when a placeholder value is requested from this hook
* *
* @param player {@link OfflinePlayer} to request the placeholder value for, null if not needed for a * @param player {@link OfflinePlayer} to request the placeholder value for, null if not needed for a
* player * player
* @param params String passed to the hook to determine what value to return * @param params String passed to the hook to determine what value to return
* @return value for the requested player and params * @return value for the requested player and params
*/ */
public String onRequest(OfflinePlayer player, String params) { @Nullable
if (player != null && player.isOnline()) { public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params)
return onPlaceholderRequest((Player) player, params); {
} if (player != null && player.isOnline())
{
return onPlaceholderRequest((Player) player, params);
}
return onPlaceholderRequest(null, params); return onPlaceholderRequest(null, params);
} }
/**
* called when a placeholder is requested from this hook
*
* @param player {@link Player} to request the placeholder value for, null if not needed for a player
* @param params String passed to the hook to determine what value to return
* @return value for the requested player and params
*/
@Nullable
@Deprecated
public String onPlaceholderRequest(@Nullable final Player player, @NotNull final String params)
{
return null;
}
/**
* called when a placeholder is requested from this hook
*
* @param player {@link Player} to request the placeholder value for, null if not needed for a player
* @param params String passed to the hook to determine what value to return
* @return value for the requested player and params
*/
public String onPlaceholderRequest(Player player, String params) {
return null;
}
} }

View File

@ -28,186 +28,207 @@ import me.clip.placeholderapi.util.FileUtil;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File; import java.io.File;
import java.lang.reflect.Constructor;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.logging.Level;
public final class ExpansionManager { public final class ExpansionManager
private final PlaceholderAPIPlugin plugin; {
public ExpansionManager(PlaceholderAPIPlugin instance) { @NotNull
plugin = instance; private final File folder;
@NotNull
private final PlaceholderAPIPlugin plugin;
File f = new File(PlaceholderAPIPlugin.getInstance().getDataFolder(), "expansions"); public ExpansionManager(@NotNull final PlaceholderAPIPlugin plugin)
if (!f.exists()) { {
f.mkdirs(); this.plugin = plugin;
} this.folder = new File(plugin.getDataFolder(), "expansions");
}
public PlaceholderExpansion getRegisteredExpansion(String name) { if (!this.folder.exists() && !folder.mkdirs())
for (Entry<String, PlaceholderHook> hook : PlaceholderAPI.getPlaceholders().entrySet()) { {
if (hook.getValue() instanceof PlaceholderExpansion) { plugin.getLogger().log(Level.WARNING, "failed to create expansions folder!");
if (name.equalsIgnoreCase(hook.getKey())) { }
return (PlaceholderExpansion) hook.getValue(); }
}
}
}
return null; public PlaceholderExpansion getRegisteredExpansion(String name)
} {
for (Entry<String, PlaceholderHook> hook : PlaceholderAPI.getPlaceholders().entrySet())
{
if (hook.getValue() instanceof PlaceholderExpansion)
{
if (name.equalsIgnoreCase(hook.getKey()))
{
return (PlaceholderExpansion) hook.getValue();
}
}
}
public boolean registerExpansion(PlaceholderExpansion expansion) { return null;
if (expansion == null || expansion.getIdentifier() == null) { }
return false;
}
if (expansion instanceof Configurable) { public boolean registerExpansion(@NotNull final PlaceholderExpansion expansion)
Map<String, Object> defaults = ((Configurable) expansion).getDefaults(); {
String pre = "expansions." + expansion.getIdentifier() + "."; if (expansion.getIdentifier() == null)
FileConfiguration cfg = plugin.getConfig(); {
boolean save = false; return false;
}
if (defaults != null) { if (expansion instanceof Configurable)
for (Entry<String, Object> entries : defaults.entrySet()) { {
if (entries.getKey() == null || entries.getKey().isEmpty()) { Map<String, Object> defaults = ((Configurable) expansion).getDefaults();
continue; String pre = "expansions." + expansion.getIdentifier() + ".";
} FileConfiguration cfg = plugin.getConfig();
boolean save = false;
if (entries.getValue() == null) { if (defaults != null)
if (cfg.contains(pre + entries.getKey())) { {
save = true; for (Entry<String, Object> entries : defaults.entrySet())
cfg.set(pre + entries.getKey(), null); {
} if (entries.getKey() == null || entries.getKey().isEmpty())
} else { {
if (!cfg.contains(pre + entries.getKey())) { continue;
save = true; }
cfg.set(pre + entries.getKey(), entries.getValue());
}
}
}
}
if (save) { if (entries.getValue() == null)
plugin.saveConfig(); {
plugin.reloadConfig(); if (cfg.contains(pre + entries.getKey()))
} {
} save = true;
cfg.set(pre + entries.getKey(), null);
}
}
else
{
if (!cfg.contains(pre + entries.getKey()))
{
save = true;
cfg.set(pre + entries.getKey(), entries.getValue());
}
}
}
}
if (expansion instanceof VersionSpecific) { if (save)
VersionSpecific nms = (VersionSpecific) expansion; {
if (!nms.isCompatibleWith(PlaceholderAPIPlugin.getServerVersion())) { plugin.saveConfig();
plugin.getLogger() plugin.reloadConfig();
.info( }
"Your server version is not compatible with expansion: " + expansion.getIdentifier() }
+ " version: " + expansion.getVersion());
return false;
}
}
if (!expansion.canRegister()) { if (expansion instanceof VersionSpecific)
return false; {
} VersionSpecific nms = (VersionSpecific) expansion;
if (!nms.isCompatibleWith(PlaceholderAPIPlugin.getServerVersion()))
{
plugin.getLogger()
.info(
"Your server version is not compatible with expansion: " + expansion.getIdentifier()
+ " version: " + expansion.getVersion());
return false;
}
}
if (!expansion.register()) { if (!expansion.canRegister() || !expansion.register())
return false; {
} return false;
}
if (expansion instanceof Listener) { if (expansion instanceof Listener)
Listener l = (Listener) expansion; {
Bukkit.getPluginManager().registerEvents(l, plugin); Bukkit.getPluginManager().registerEvents(((Listener) expansion), plugin);
} }
plugin.getLogger().info("Successfully registered expansion: " + expansion.getIdentifier()); plugin.getLogger().info("Successfully registered expansion: " + expansion.getIdentifier());
if (expansion instanceof Taskable) { if (expansion instanceof Taskable)
((Taskable) expansion).start(); {
} ((Taskable) expansion).start();
}
if (plugin.getExpansionCloud() != null) { if (plugin.getExpansionCloud() != null)
CloudExpansion ce = plugin.getExpansionCloud().getCloudExpansion(expansion.getIdentifier()); {
final CloudExpansion cloudExpansion = plugin.getExpansionCloud().getCloudExpansion(expansion.getIdentifier());
if (ce != null) { if (cloudExpansion != null)
ce.setHasExpansion(true); {
if (!ce.getLatestVersion().equals(expansion.getVersion())) { cloudExpansion.setHasExpansion(true);
ce.setShouldUpdate(true); if (!cloudExpansion.getLatestVersion().equals(expansion.getVersion()))
} {
} cloudExpansion.setShouldUpdate(true);
} }
}
}
return true; return true;
} }
public PlaceholderExpansion registerExpansion(String fileName) { @Nullable
List<Class<?>> subs = FileUtil.getClasses("expansions", fileName, PlaceholderExpansion.class); public PlaceholderExpansion registerExpansion(@NotNull final String fileName)
if (subs == null || subs.isEmpty()) { {
return null; final List<Class<? extends PlaceholderExpansion>> subs = FileUtil.getClasses(folder, PlaceholderExpansion.class, fileName);
} if (subs.isEmpty())
{
return null;
}
// only register the first instance found as an expansion jar should only have 1 class // only register the first instance found as an expansion jar should only have 1 class
// extending PlaceholderExpansion // extending PlaceholderExpansion
PlaceholderExpansion ex = createInstance(subs.get(0)); final PlaceholderExpansion expansion = createInstance(subs.get(0));
if (registerExpansion(ex)) { if (expansion != null && registerExpansion(expansion))
return ex; {
} return expansion;
}
return null; return null;
} }
public void registerAllExpansions() { public void registerAllExpansions()
if (plugin == null) { {
return; final List<@NotNull Class<? extends PlaceholderExpansion>> subs = FileUtil.getClasses(folder, PlaceholderExpansion.class);
} if (subs.isEmpty())
{
return;
}
List<Class<?>> subs = FileUtil.getClasses("expansions", null, PlaceholderExpansion.class); for (final Class<? extends PlaceholderExpansion> clazz : subs)
if (subs == null || subs.isEmpty()) { {
return; final PlaceholderExpansion expansion = createInstance(clazz);
} if (expansion == null)
{
continue;
}
for (Class<?> klass : subs) { try
PlaceholderExpansion ex = createInstance(klass); {
if (ex != null) { registerExpansion(expansion);
try { }
registerExpansion(ex); catch (final Exception ex)
} catch (Exception e) { {
plugin.getLogger().info("Couldn't register " + ex.getIdentifier() + " expansion"); plugin.getLogger().log(Level.WARNING, "Couldn't register " + expansion.getIdentifier() + " expansion", ex);
e.printStackTrace(); }
} }
} }
}
}
private PlaceholderExpansion createInstance(Class<?> klass) { @Nullable
if (klass == null) { private PlaceholderExpansion createInstance(@NotNull final Class<? extends PlaceholderExpansion> clazz)
return null; {
} try
{
return clazz.getDeclaredConstructor().newInstance();
}
catch (final Throwable ex)
{
plugin.getLogger().log(Level.SEVERE, "Failed to load placeholder expansion from class: " + clazz.getName(), ex);
}
PlaceholderExpansion ex = null; return null;
if (!PlaceholderExpansion.class.isAssignableFrom(klass)) { }
return null;
}
try {
Constructor<?>[] c = klass.getConstructors();
if (c.length == 0) {
ex = (PlaceholderExpansion) klass.newInstance();
} else {
for (Constructor<?> con : c) {
if (con.getParameterTypes().length == 0) {
ex = (PlaceholderExpansion) klass.newInstance();
break;
}
}
}
} catch (Throwable t) {
plugin.getLogger()
.severe("Failed to init placeholder expansion from class: " + klass.getName());
plugin.getLogger().severe(t.getMessage());
}
return ex;
}
} }

View File

@ -0,0 +1,129 @@
package me.clip.placeholderapi.replacer;
import me.clip.placeholderapi.PlaceholderHook;
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
{
@NotNull
private final Closure closure;
public CharsReplacer(@NotNull final Closure closure)
{
this.closure = closure;
}
@Override
public @NotNull String apply(@NotNull final String text, @Nullable final OfflinePlayer player, @NotNull final Function<String, @Nullable PlaceholderHook> lookup)
{
final char[] chars = text.toCharArray();
final StringBuilder builder = new StringBuilder(text.length());
final StringBuilder identifier = new StringBuilder();
final StringBuilder parameters = new StringBuilder();
for (int i = 0; i < chars.length; i++)
{
final char l = chars[i];
if (l == '&' && ++i < chars.length)
{
final char c = chars[i];
if (c != '0' && c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8' && c != '9' && c != 'a' && c != 'b' && c != 'c' && c != 'd' && c != 'e' && c != 'f' && c != 'k' && c != 'l' && c != 'm' && c != 'o' && c != 'r' && c != 'x')
{
builder.append(l).append(c);
}
else
{
builder.append('§').append(c);
}
continue;
}
if (l != closure.head || i + 1 >= chars.length)
{
builder.append(l);
continue;
}
boolean identified = false;
boolean oopsitsbad = false;
while (++i < chars.length)
{
final char p = chars[i];
if (p == closure.tail)
{
break;
}
if (p == ' ')
{
oopsitsbad = true;
break;
}
if (p == '_' && !identified)
{
identified = true;
continue;
}
if (identified)
{
parameters.append(p);
}
else
{
identifier.append(p);
}
}
final String identifierString = identifier.toString();
final String parametersString = parameters.toString();
identifier.setLength(0);
parameters.setLength(0);
if (oopsitsbad)
{
builder.append(closure.head).append(identifierString);
if (identified)
{
builder.append('_').append(parametersString);
}
builder.append(' ');
continue;
}
final PlaceholderHook placeholder = lookup.apply(identifierString);
if (placeholder == null)
{
builder.append(closure.head).append(identifierString).append('_').append(parametersString).append(closure.tail);
continue;
}
final String replacement = placeholder.onRequest(player, parametersString);
if (replacement == null)
{
builder.append(closure.head).append(identifierString).append('_').append(parametersString).append(closure.tail);
continue;
}
builder.append(replacement);
}
return builder.toString();
}
}

View File

@ -0,0 +1,55 @@
package me.clip.placeholderapi.replacer;
import me.clip.placeholderapi.PlaceholderHook;
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
{
@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));
}
@Override
public @NotNull String apply(@NotNull final String text, @Nullable final OfflinePlayer player, @NotNull final Function<String, @Nullable PlaceholderHook> lookup)
{
final Matcher matcher = pattern.matcher(text);
if (!matcher.find())
{
return text;
}
final StringBuffer builder = new StringBuffer();
do
{
final String identifier = matcher.group("identifier");
final String parameters = matcher.group("parameters");
final PlaceholderHook hook = lookup.apply(identifier);
if (hook == null)
{
continue;
}
final String requested = hook.onRequest(player, parameters);
matcher.appendReplacement(builder, requested != null ? requested : matcher.group(0));
}
while (matcher.find());
return ChatColor.translateAlternateColorCodes('&', matcher.appendTail(builder).toString());
}
}

View File

@ -0,0 +1,32 @@
package me.clip.placeholderapi.replacer;
import me.clip.placeholderapi.PlaceholderHook;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.function.Function;
public interface Replacer
{
@NotNull
String apply(@NotNull final String text, @Nullable final OfflinePlayer player, @NotNull final Function<String, @Nullable PlaceholderHook> lookup);
enum Closure
{
BRACKET('{', '}'),
PERCENT('%', '%');
public final char head, tail;
Closure(final char head, final char tail)
{
this.head = head;
this.tail = tail;
}
}
}

View File

@ -20,89 +20,85 @@
*/ */
package me.clip.placeholderapi.util; package me.clip.placeholderapi.util;
import me.clip.placeholderapi.PlaceholderAPIPlugin; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File; import java.io.File;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
import java.util.jar.JarInputStream; import java.util.jar.JarInputStream;
public class FileUtil { public class FileUtil
{
public static List<Class<?>> getClasses(String folder, Class<?> type) { @NotNull
return getClasses(folder, null, type); public static <T> List<@NotNull Class<? extends T>> getClasses(@NotNull final File folder, @NotNull final Class<T> clazz)
} {
return getClasses(folder, clazz, null);
}
public static List<Class<?>> getClasses(String folder, String fileName, Class<?> type) { @NotNull
List<Class<?>> list = new ArrayList<>(); public static <T> List<@NotNull Class<? extends T>> getClasses(@NotNull final File folder, @NotNull final Class<T> clazz, @Nullable final String target)
{
if (!folder.exists())
{
return Collections.emptyList();
}
try { try
File f = new File(PlaceholderAPIPlugin.getInstance().getDataFolder(), folder); {
if (!f.exists()) { final FilenameFilter filter =
return list; (dir, name) -> name.endsWith(".jar") && (target == null || name.replace(".jar", "").equalsIgnoreCase(target.replace(".jar", "")));
}
FilenameFilter fileNameFilter = (dir, name) -> { final File[] jars = folder.listFiles(filter);
if (fileName != null) { if (jars == null)
return name.endsWith(".jar") && name.replace(".jar", "") {
.equalsIgnoreCase(fileName.replace(".jar", "")); return Collections.emptyList();
} }
return name.endsWith(".jar"); final List<@NotNull Class<? extends T>> list = new ArrayList<>();
};
File[] jars = f.listFiles(fileNameFilter); for (File file : jars)
if (jars == null) { {
return list; gather(file.toURI().toURL(), clazz, list);
} }
for (File file : jars) { return list;
list = gather(file.toURI().toURL(), list, type); }
} catch (Throwable t)
{
// THIS SHOULD NOT BE EATEN LIKE THIS.
}
return list; return Collections.emptyList();
} catch (Throwable t) { }
}
return null; private static <T> void gather(@NotNull final URL jar, @NotNull final Class<T> clazz, @NotNull final List<@NotNull Class<? extends T>> list) throws IOException, ClassNotFoundException
} {
try (final URLClassLoader loader = new URLClassLoader(new URL[]{jar}, clazz.getClassLoader()); final JarInputStream stream = new JarInputStream(jar.openStream()))
{
JarEntry entry;
while ((entry = stream.getNextJarEntry()) != null)
{
final String name = entry.getName();
if (name == null || name.isEmpty() || !name.endsWith(".class"))
{
continue;
}
private static List<Class<?>> gather(URL jar, List<Class<?>> list, Class<?> clazz) { final Class<?> loaded = loader.loadClass(name.substring(0, name.lastIndexOf('.')).replace('/', '.'));
if (list == null) { if (clazz.isAssignableFrom(loaded))
list = new ArrayList<>(); {
} list.add(loaded.asSubclass(clazz));
}
}
}
}
try (URLClassLoader cl = new URLClassLoader(new URL[]{jar}, clazz.getClassLoader());
JarInputStream jis = new JarInputStream(jar.openStream())) {
while (true) {
JarEntry j = jis.getNextJarEntry();
if (j == null) {
break;
}
String name = j.getName();
if (name == null || name.isEmpty()) {
continue;
}
if (name.endsWith(".class")) {
name = name.replace("/", ".");
String cname = name.substring(0, name.lastIndexOf(".class"));
Class<?> c = cl.loadClass(cname);
if (clazz.isAssignableFrom(c)) {
list.add(c);
}
}
}
} catch (Throwable t) {
}
return list;
}
} }

View File

@ -23,21 +23,37 @@ package me.clip.placeholderapi.util;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays; import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public final class Msg { public final class Msg
public static void msg(CommandSender s, String... msg) { {
s.sendMessage(Arrays.stream(msg).filter(Objects::nonNull).map(Msg::color).collect(Collectors.joining("\n")));
}
public static void broadcast(String... msg) { public static void msg(@NotNull final CommandSender sender, @NotNull final String... messages)
Arrays.stream(msg).filter(Objects::nonNull).map(Msg::color).forEach(Bukkit::broadcastMessage); {
} if (messages.length == 0)
{
return;
}
sender.sendMessage(Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n")));
}
public static void broadcast(@NotNull final String... messages)
{
if (messages.length == 0)
{
return;
}
Bukkit.broadcastMessage(Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n")));
}
public static String color(@NotNull final String text)
{
return ChatColor.translateAlternateColorCodes('&', text);
}
public static String color(String text) {
return ChatColor.translateAlternateColorCodes('&', text);
}
} }

View File

@ -0,0 +1,187 @@
package me.clip.placeholderapi;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import me.clip.placeholderapi.replacer.CharsReplacer;
import me.clip.placeholderapi.replacer.RegexReplacer;
import me.clip.placeholderapi.replacer.Replacer;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
import java.util.function.Function;
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%";
ImmutableMap<String, PlaceholderHook> PLACEHOLDERS = ImmutableMap.<String, PlaceholderHook>builder()
.put("player", new MockPlayerPlaceholderHook())
.build();
Replacer CHARS_REPLACER = new CharsReplacer(Replacer.Closure.PERCENT);
Replacer REGEX_REPLACER = new RegexReplacer(Replacer.Closure.PERCENT);
Replacer TESTS_REPLACER = new Replacer()
{
private final Set<Character> COLOR_CODES = ImmutableSet.of('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'k', 'l', 'm', 'o', 'r', 'x');
private final boolean colorize = true;
private final Replacer.Closure closure = Replacer.Closure.PERCENT;
@Override
public @NotNull String apply(final @NotNull String text, final @Nullable OfflinePlayer player, final @NotNull Function<String, @Nullable PlaceholderHook> lookup)
{
char[] chars = text.toCharArray();
StringBuilder builder = new StringBuilder(chars.length);
// This won't cause memory leaks. It's inside a method. And we want to use setLength instead of
// creating a new string builder to use the maximum capacity and avoid initializing new objects.
StringBuilder identifier = new StringBuilder(50);
PlaceholderHook handler = null;
// Stages:
// Stage -1: Look for the color code in the next character.
// Stage 0: No closures detected, or the detected identifier is invalid. We're going forward while appending the characters normally.
// Stage 1: The closure has been detected, looking for the placeholder identifier...
// Stage 2: Detected the identifier and the parameter. Translating the placeholder...
int stage = 0;
for (char ch : chars)
{
if (stage == -1 && COLOR_CODES.contains(ch))
{
builder.append(ChatColor.COLOR_CHAR).append(ch);
stage = 0;
continue;
}
// Check if the placeholder starts or ends.
if (ch == closure.head || ch == closure.tail)
{
// If the placeholder ends.
if (stage == 2)
{
String parameter = identifier.toString();
String translated = handler.onRequest(player, parameter);
if (translated == null)
{
String name = "";
builder.append(closure.head).append(name).append('_').append(parameter).append(closure.tail);
}
else
{
builder.append(translated);
}
identifier.setLength(0);
stage = 0;
continue;
}
else if (stage == 1)
{ // If it just started | Double closures | If it's still hasn't detected the indentifier, reset.
builder.append(closure.head).append(identifier);
}
identifier.setLength(0);
stage = 1;
continue;
}
// Placeholder identifier started.
if (stage == 1)
{
// Compare the current character with the idenfitier's.
// We reached the end of our identifier.
if (ch == '_')
{
handler = lookup.apply(identifier.toString());
if (handler == null)
{
builder.append(closure.head).append(identifier).append('_');
stage = 0;
}
else
{
identifier.setLength(0);
stage = 2;
}
continue;
}
// Keep building the identifier name.
identifier.append(ch);
continue;
}
// Building the placeholder parameter.
if (stage == 2)
{
identifier.append(ch);
continue;
}
// Nothing placeholder related was found.
if (colorize && ch == '&')
{
stage = -1;
continue;
}
builder.append(ch);
}
if (identifier != null)
{
if (stage > 0)
{
builder.append(closure.tail);
}
builder.append(identifier);
}
return builder.toString();
}
};
final class MockPlayerPlaceholderHook extends PlaceholderHook
{
public static final String PLAYER_X = String.valueOf(10);
public static final String PLAYER_Y = String.valueOf(20);
public static final String PLAYER_Z = String.valueOf(30);
public static final String PLAYER_NAME = "Sxtanna";
@Override
public String onRequest(final OfflinePlayer player, final String params)
{
final String[] parts = params.split("_");
if (parts.length == 0)
{
return null;
}
switch (parts[0])
{
case "name":
return PLAYER_NAME;
case "x":
return PLAYER_X;
case "y":
return PLAYER_Y;
case "z":
return PLAYER_Z;
}
return null;
}
}
}

View File

@ -0,0 +1,45 @@
package me.clip.placeholderapi.replacer;
import me.clip.placeholderapi.Values;
import org.openjdk.jmh.annotations.Benchmark;
public class ReplacerBenchmarks
{
@Benchmark
public void measureCharsReplacerSmallText()
{
Values.CHARS_REPLACER.apply(Values.SMALL_TEXT, null, Values.PLACEHOLDERS::get);
}
@Benchmark
public void measureRegexReplacerSmallText()
{
Values.REGEX_REPLACER.apply(Values.SMALL_TEXT, null, Values.PLACEHOLDERS::get);
}
@Benchmark
public void measureCharsReplacerLargeText()
{
Values.CHARS_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get);
}
@Benchmark
public void measureRegexReplacerLargeText()
{
Values.REGEX_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get);
}
@Benchmark
public void measureTestsReplacerSmallText()
{
Values.TESTS_REPLACER.apply(Values.SMALL_TEXT, null, Values.PLACEHOLDERS::get);
}
@Benchmark
public void measureTestsReplacerLargeText()
{
Values.TESTS_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get);
}
}

View File

@ -0,0 +1,67 @@
package me.clip.placeholderapi.replacer;
import me.clip.placeholderapi.Values;
import org.junit.jupiter.api.Test;
import static me.clip.placeholderapi.Values.MockPlayerPlaceholderHook.PLAYER_NAME;
import static me.clip.placeholderapi.Values.MockPlayerPlaceholderHook.PLAYER_X;
import static me.clip.placeholderapi.Values.MockPlayerPlaceholderHook.PLAYER_Y;
import static me.clip.placeholderapi.Values.MockPlayerPlaceholderHook.PLAYER_Z;
import static org.junit.jupiter.api.Assertions.assertEquals;
public final class ReplacerUnitTester
{
@Test
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));
}
@Test
void testCharsReplacerProducesExpectedSentence()
{
assertEquals(String.format("My name is %s and my location is (%s, %s, %s), this placeholder is invalid %%server_name%%", PLAYER_NAME, PLAYER_X, PLAYER_Y, PLAYER_Z), Values.CHARS_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get));
}
@Test
void 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);
assertEquals(resultChars, resultRegex);
assertEquals(PLAYER_NAME, resultChars);
}
@Test
void testResultsAreTheSameNoReplacement()
{
final String resultChars = Values.CHARS_REPLACER.apply("%player_location%", null, Values.PLACEHOLDERS::get);
final String resultRegex = Values.REGEX_REPLACER.apply("%player_location%", null, Values.PLACEHOLDERS::get);
assertEquals(resultChars, resultRegex);
}
@Test
void testCharsReplacerIgnoresMalformed()
{
final String text = "10% and %hello world 15%";
assertEquals(text, Values.CHARS_REPLACER.apply(text, null, Values.PLACEHOLDERS::get));
}
}