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.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
*
* @param player {@link OfflinePlayer} 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 onRequest(OfflinePlayer player, String params) {
if (player != null && player.isOnline()) {
return onPlaceholderRequest((Player) player, params);
}
/**
* 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
* player
* @param params String passed to the hook to determine what value to return
* @return value for the requested player and params
*/
@Nullable
public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params)
{
if (player != null && player.isOnline())
{
return onPlaceholderRequest((Player) player, params);
}
return onPlaceholderRequest(null, params);
}
return onPlaceholderRequest(null, params);
}
/**
* 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.configuration.file.FileConfiguration;
import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
public final class ExpansionManager {
private final PlaceholderAPIPlugin plugin;
public final class ExpansionManager
{
public ExpansionManager(PlaceholderAPIPlugin instance) {
plugin = instance;
@NotNull
private final File folder;
@NotNull
private final PlaceholderAPIPlugin plugin;
File f = new File(PlaceholderAPIPlugin.getInstance().getDataFolder(), "expansions");
if (!f.exists()) {
f.mkdirs();
}
}
public ExpansionManager(@NotNull final PlaceholderAPIPlugin plugin)
{
this.plugin = plugin;
this.folder = new File(plugin.getDataFolder(), "expansions");
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();
}
}
}
if (!this.folder.exists() && !folder.mkdirs())
{
plugin.getLogger().log(Level.WARNING, "failed to create expansions folder!");
}
}
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) {
if (expansion == null || expansion.getIdentifier() == null) {
return false;
}
return null;
}
if (expansion instanceof Configurable) {
Map<String, Object> defaults = ((Configurable) expansion).getDefaults();
String pre = "expansions." + expansion.getIdentifier() + ".";
FileConfiguration cfg = plugin.getConfig();
boolean save = false;
public boolean registerExpansion(@NotNull final PlaceholderExpansion expansion)
{
if (expansion.getIdentifier() == null)
{
return false;
}
if (defaults != null) {
for (Entry<String, Object> entries : defaults.entrySet()) {
if (entries.getKey() == null || entries.getKey().isEmpty()) {
continue;
}
if (expansion instanceof Configurable)
{
Map<String, Object> defaults = ((Configurable) expansion).getDefaults();
String pre = "expansions." + expansion.getIdentifier() + ".";
FileConfiguration cfg = plugin.getConfig();
boolean save = false;
if (entries.getValue() == null) {
if (cfg.contains(pre + entries.getKey())) {
save = true;
cfg.set(pre + entries.getKey(), null);
}
} else {
if (!cfg.contains(pre + entries.getKey())) {
save = true;
cfg.set(pre + entries.getKey(), entries.getValue());
}
}
}
}
if (defaults != null)
{
for (Entry<String, Object> entries : defaults.entrySet())
{
if (entries.getKey() == null || entries.getKey().isEmpty())
{
continue;
}
if (save) {
plugin.saveConfig();
plugin.reloadConfig();
}
}
if (entries.getValue() == null)
{
if (cfg.contains(pre + entries.getKey()))
{
save = true;
cfg.set(pre + entries.getKey(), null);
}
}
else
{
if (!cfg.contains(pre + entries.getKey()))
{
save = true;
cfg.set(pre + entries.getKey(), entries.getValue());
}
}
}
}
if (expansion instanceof VersionSpecific) {
VersionSpecific nms = (VersionSpecific) expansion;
if (!nms.isCompatibleWith(PlaceholderAPIPlugin.getServerVersion())) {
plugin.getLogger()
.info(
"Your server version is not compatible with expansion: " + expansion.getIdentifier()
+ " version: " + expansion.getVersion());
return false;
}
}
if (save)
{
plugin.saveConfig();
plugin.reloadConfig();
}
}
if (!expansion.canRegister()) {
return false;
}
if (expansion instanceof VersionSpecific)
{
VersionSpecific nms = (VersionSpecific) expansion;
if (!nms.isCompatibleWith(PlaceholderAPIPlugin.getServerVersion()))
{
plugin.getLogger()
.info(
"Your server version is not compatible with expansion: " + expansion.getIdentifier()
+ " version: " + expansion.getVersion());
return false;
}
}
if (!expansion.register()) {
return false;
}
if (!expansion.canRegister() || !expansion.register())
{
return false;
}
if (expansion instanceof Listener) {
Listener l = (Listener) expansion;
Bukkit.getPluginManager().registerEvents(l, plugin);
}
if (expansion instanceof Listener)
{
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) {
((Taskable) expansion).start();
}
if (expansion instanceof Taskable)
{
((Taskable) expansion).start();
}
if (plugin.getExpansionCloud() != null) {
CloudExpansion ce = plugin.getExpansionCloud().getCloudExpansion(expansion.getIdentifier());
if (plugin.getExpansionCloud() != null)
{
final CloudExpansion cloudExpansion = plugin.getExpansionCloud().getCloudExpansion(expansion.getIdentifier());
if (ce != null) {
ce.setHasExpansion(true);
if (!ce.getLatestVersion().equals(expansion.getVersion())) {
ce.setShouldUpdate(true);
}
}
}
if (cloudExpansion != null)
{
cloudExpansion.setHasExpansion(true);
if (!cloudExpansion.getLatestVersion().equals(expansion.getVersion()))
{
cloudExpansion.setShouldUpdate(true);
}
}
}
return true;
}
return true;
}
public PlaceholderExpansion registerExpansion(String fileName) {
List<Class<?>> subs = FileUtil.getClasses("expansions", fileName, PlaceholderExpansion.class);
if (subs == null || subs.isEmpty()) {
return null;
}
@Nullable
public PlaceholderExpansion registerExpansion(@NotNull final String fileName)
{
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
// extending PlaceholderExpansion
PlaceholderExpansion ex = createInstance(subs.get(0));
if (registerExpansion(ex)) {
return ex;
}
// only register the first instance found as an expansion jar should only have 1 class
// extending PlaceholderExpansion
final PlaceholderExpansion expansion = createInstance(subs.get(0));
if (expansion != null && registerExpansion(expansion))
{
return expansion;
}
return null;
}
return null;
}
public void registerAllExpansions() {
if (plugin == null) {
return;
}
public void registerAllExpansions()
{
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);
if (subs == null || subs.isEmpty()) {
return;
}
for (final Class<? extends PlaceholderExpansion> clazz : subs)
{
final PlaceholderExpansion expansion = createInstance(clazz);
if (expansion == null)
{
continue;
}
for (Class<?> klass : subs) {
PlaceholderExpansion ex = createInstance(klass);
if (ex != null) {
try {
registerExpansion(ex);
} catch (Exception e) {
plugin.getLogger().info("Couldn't register " + ex.getIdentifier() + " expansion");
e.printStackTrace();
}
}
}
}
try
{
registerExpansion(expansion);
}
catch (final Exception ex)
{
plugin.getLogger().log(Level.WARNING, "Couldn't register " + expansion.getIdentifier() + " expansion", ex);
}
}
}
private PlaceholderExpansion createInstance(Class<?> klass) {
if (klass == null) {
return null;
}
@Nullable
private PlaceholderExpansion createInstance(@NotNull final Class<? extends PlaceholderExpansion> clazz)
{
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;
if (!PlaceholderExpansion.class.isAssignableFrom(klass)) {
return null;
}
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;
import me.clip.placeholderapi.PlaceholderAPIPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
public class FileUtil {
public class FileUtil
{
public static List<Class<?>> getClasses(String folder, Class<?> type) {
return getClasses(folder, null, type);
}
@NotNull
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) {
List<Class<?>> list = new ArrayList<>();
@NotNull
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 {
File f = new File(PlaceholderAPIPlugin.getInstance().getDataFolder(), folder);
if (!f.exists()) {
return list;
}
try
{
final FilenameFilter filter =
(dir, name) -> name.endsWith(".jar") && (target == null || name.replace(".jar", "").equalsIgnoreCase(target.replace(".jar", "")));
FilenameFilter fileNameFilter = (dir, name) -> {
if (fileName != null) {
return name.endsWith(".jar") && name.replace(".jar", "")
.equalsIgnoreCase(fileName.replace(".jar", ""));
}
final File[] jars = folder.listFiles(filter);
if (jars == null)
{
return Collections.emptyList();
}
return name.endsWith(".jar");
};
final List<@NotNull Class<? extends T>> list = new ArrayList<>();
File[] jars = f.listFiles(fileNameFilter);
if (jars == null) {
return list;
}
for (File file : jars)
{
gather(file.toURI().toURL(), clazz, list);
}
for (File file : jars) {
list = gather(file.toURI().toURL(), list, type);
}
return list;
}
catch (Throwable t)
{
// THIS SHOULD NOT BE EATEN LIKE THIS.
}
return list;
} catch (Throwable t) {
}
return Collections.emptyList();
}
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) {
if (list == null) {
list = new ArrayList<>();
}
final Class<?> loaded = loader.loadClass(name.substring(0, name.lastIndexOf('.')).replace('/', '.'));
if (clazz.isAssignableFrom(loaded))
{
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.ChatColor;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
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 final class Msg
{
public static void broadcast(String... msg) {
Arrays.stream(msg).filter(Objects::nonNull).map(Msg::color).forEach(Bukkit::broadcastMessage);
}
public static void msg(@NotNull final CommandSender sender, @NotNull final String... messages)
{
if (messages.length == 0)
{
return;
}
sender.sendMessage(Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n")));
}
public static void broadcast(@NotNull final String... messages)
{
if (messages.length == 0)
{
return;
}
Bukkit.broadcastMessage(Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n")));
}
public static String color(@NotNull final String text)
{
return ChatColor.translateAlternateColorCodes('&', text);
}
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));
}
}