Code cleanup and PlaceholderAPI script variable added (use PlaceholderAPI.static to access it)

This commit is contained in:
iGabyTM 2020-03-11 21:20:18 +02:00
parent 69a514f62d
commit be00944461
7 changed files with 781 additions and 772 deletions

View File

@ -21,229 +21,226 @@
package com.extendedclip.papi.expansion.javascript;
import com.extendedclip.papi.expansion.javascript.cloud.GithubScriptManager;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import me.clip.placeholderapi.expansion.Cacheable;
import me.clip.placeholderapi.expansion.Configurable;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandMap;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import me.clip.placeholderapi.expansion.Cacheable;
import me.clip.placeholderapi.expansion.Configurable;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandMap;
import java.lang.reflect.Field;
import java.util.*;
public class JavascriptExpansion extends PlaceholderExpansion implements Cacheable, Configurable {
private ScriptEngine globalEngine = null;
private JavascriptPlaceholdersConfig config;
private final Set<JavascriptPlaceholder> scripts = new HashSet<>();
private final String VERSION = getClass().getPackage().getImplementationVersion();
private static JavascriptExpansion instance;
private boolean debug;
private GithubScriptManager githubScripts;
private JavascriptExpansionCommands commands;
private CommandMap commandMap;
private ScriptEngine globalEngine = null;
private JavascriptPlaceholdersConfig config;
private final Set<JavascriptPlaceholder> scripts = new HashSet<>();
private final String VERSION = getClass().getPackage().getImplementationVersion();
private static JavascriptExpansion instance;
private boolean debug;
private GithubScriptManager githubScripts;
private JavascriptExpansionCommands commands;
private CommandMap commandMap;
public JavascriptExpansion() {
instance = this;
try {
final Field f = Bukkit.getServer().getClass().getDeclaredField("commandMap");
f.setAccessible(true);
commandMap = (CommandMap) f.get(Bukkit.getServer());
} catch (Exception e) {
e.printStackTrace();
}
}
public JavascriptExpansion() {
instance = this;
try {
final Field f = Bukkit.getServer().getClass().getDeclaredField("commandMap");
f.setAccessible(true);
commandMap = (CommandMap) f.get(Bukkit.getServer());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String getAuthor() {
return "clip";
}
@Override
public String getAuthor() {
return "clip";
}
@Override
public String getIdentifier() {
return "javascript";
}
@Override
public String getIdentifier() {
return "javascript";
}
@Override
public String getPlugin() {
return null;
}
@Override
public String getVersion() {
return VERSION;
}
@Override
public boolean register() {
if (globalEngine == null) {
try {
globalEngine = new ScriptEngineManager().getEngineByName(getString("engine", "nashorn"));
} catch (NullPointerException ex) {
getPlaceholderAPI().getLogger().warning("Javascript engine type was invalid! Defaulting to 'nashorn'");
globalEngine = new ScriptEngineManager().getEngineByName("nashorn");
}
}
debug = (boolean) get("debug", false);
config = new JavascriptPlaceholdersConfig(this);
config.loadPlaceholders();
if (debug) {
System.out.println("Java version: " + System.getProperty("java.version"));
@Override
public String getPlugin() {
return null;
}
ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> factories = manager.getEngineFactories();
System.out.println("displaying all script engine factories:");
for (ScriptEngineFactory factory : factories) {
System.out.println("Engine name: " + factory.getEngineName());
System.out.println("version: " + factory.getEngineVersion());
System.out.println("lang name: " + factory.getLanguageName());
System.out.println("lang version: " + factory.getLanguageVersion());
System.out.println("extensions: " + factory.getExtensions());
System.out.println("mime types: " + factory.getMimeTypes());
System.out.println("names: " + factory.getNames());
}
}
if ((Boolean) get("github_script_downloads", false)) {
githubScripts = new GithubScriptManager(this);
githubScripts.fetch();
}
@Override
public String getVersion() {
return VERSION;
}
registerCommand();
return super.register();
}
@Override
public void clear() {
unregisterCommand();
scripts.forEach(s -> {
s.saveData();
s.cleanup();
});
if (githubScripts != null) {
githubScripts.clear();
githubScripts = null;
}
scripts.clear();
globalEngine = null;
instance = null;
}
@Override
public boolean register() {
if (globalEngine == null) {
try {
globalEngine = new ScriptEngineManager().getEngineByName(getString("engine", "nashorn"));
} catch (NullPointerException ex) {
getPlaceholderAPI().getLogger().warning("Javascript engine type was invalid! Defaulting to 'nashorn'");
globalEngine = new ScriptEngineManager().getEngineByName("nashorn");
}
}
@Override
public String onRequest( OfflinePlayer p, String identifier) {
if (p == null) {
return "";
}
if (scripts.isEmpty()) {
return null;
}
debug = (boolean) get("debug", false);
config = new JavascriptPlaceholdersConfig(this);
config.loadPlaceholders();
for (JavascriptPlaceholder script : scripts) {
if (identifier.startsWith(script.getIdentifier() + "_")) {
identifier = identifier.replace(script.getIdentifier() + "_", "");
return !identifier.contains(",") ? script.evaluate(p, identifier) : script.evaluate(p, identifier.split(","));
} else if (identifier.equalsIgnoreCase(script.getIdentifier())) {
return script.evaluate(p);
}
}
return null;
}
public boolean addJSPlaceholder(JavascriptPlaceholder p) {
if (p == null) {
return false;
}
if (scripts.isEmpty()) {
scripts.add(p);
return true;
}
if (scripts.stream().filter(s -> s.getIdentifier().equalsIgnoreCase(p.getIdentifier())).findFirst().orElse(null) != null) {
return false;
}
scripts.add(p);
return true;
}
public Set<JavascriptPlaceholder> getJSPlaceholders() {
return scripts;
}
public List<String> getLoadedIdentifiers() {
List<String> l = new ArrayList<>();
scripts.forEach(s -> {
l.add(s.getIdentifier());
});
return l;
}
public JavascriptPlaceholder getJSPlaceholder(String identifier) {
return scripts.stream().filter(s -> s.getIdentifier().equalsIgnoreCase(identifier)).findFirst().orElse(null);
}
public int getAmountLoaded() {
return scripts.size();
}
public ScriptEngine getGlobalEngine() {
return globalEngine;
}
if (debug) {
System.out.println("Java version: " + System.getProperty("java.version"));
public JavascriptPlaceholdersConfig getConfig() {
return config;
}
final ScriptEngineManager manager = new ScriptEngineManager();
final List<ScriptEngineFactory> factories = manager.getEngineFactories();
System.out.println("Displaying all script engine factories.");
@Override
public Map<String, Object> getDefaults() {
Map<String, Object> def = new HashMap<String, Object>();
def.put("engine", "javascript");
def.put("debug", false);
def.put("github_script_downloads", false);
return def;
}
protected int reloadScripts() {
scripts.forEach(s -> {
s.saveData();
s.cleanup();
});
scripts.clear();
config.reload();
return config.loadPlaceholders();
}
public static JavascriptExpansion getInstance() {
return instance;
}
for (ScriptEngineFactory factory : factories) {
System.out.println(factory.getEngineName());
System.out.println(" Version: " + factory.getEngineVersion());
System.out.println(" Lang name: " + factory.getLanguageName());
System.out.println(" Lang version: " + factory.getLanguageVersion());
System.out.println(" Extensions: ." + String.join(", .", factory.getExtensions()));
System.out.println(" Mime types: " + String.join(", ", factory.getMimeTypes()));
System.out.println(" Names: " + String.join(", ", factory.getNames()));
}
}
public GithubScriptManager getGithubScriptManager() {
return githubScripts;
}
githubScripts = new GithubScriptManager(this);
private boolean unregisterCommand() {
if (commandMap == null || commands == null) return false;
return commands.unregister(commandMap);
}
if ((Boolean) get("github_script_downloads", false)) {
githubScripts.fetch();
}
private boolean registerCommand() {
if (commandMap == null) return false;
commands = new JavascriptExpansionCommands(this);
commandMap.register("papi" + commands.getName(), commands);
return commands.isRegistered();
}
registerCommand();
return super.register();
}
@Override
public void clear() {
unregisterCommand();
scripts.forEach(s -> {
s.saveData();
s.cleanup();
});
if (githubScripts != null) {
githubScripts.clear();
githubScripts = null;
}
scripts.clear();
globalEngine = null;
instance = null;
}
@Override
public String onRequest(OfflinePlayer p, String identifier) {
if (p == null) {
return "";
}
if (scripts.isEmpty()) {
return null;
}
for (JavascriptPlaceholder script : scripts) {
if (identifier.startsWith(script.getIdentifier() + "_")) {
identifier = identifier.replace(script.getIdentifier() + "_", "");
return !identifier.contains(",") ? script.evaluate(p, identifier) : script.evaluate(p, identifier.split(","));
} else if (identifier.equalsIgnoreCase(script.getIdentifier())) {
return script.evaluate(p);
}
}
return null;
}
public boolean addJSPlaceholder(JavascriptPlaceholder p) {
if (p == null) {
return false;
}
if (scripts.isEmpty()) {
scripts.add(p);
return true;
}
if (scripts.stream().filter(s -> s.getIdentifier().equalsIgnoreCase(p.getIdentifier())).findFirst().orElse(null) != null) {
return false;
}
scripts.add(p);
return true;
}
public Set<JavascriptPlaceholder> getJSPlaceholders() {
return scripts;
}
public List<String> getLoadedIdentifiers() {
List<String> l = new ArrayList<>();
scripts.forEach(s -> l.add(s.getIdentifier()));
return l;
}
public JavascriptPlaceholder getJSPlaceholder(String identifier) {
return scripts.stream().filter(s -> s.getIdentifier().equalsIgnoreCase(identifier)).findFirst().orElse(null);
}
public int getAmountLoaded() {
return scripts.size();
}
public ScriptEngine getGlobalEngine() {
return globalEngine;
}
public JavascriptPlaceholdersConfig getConfig() {
return config;
}
@Override
public Map<String, Object> getDefaults() {
Map<String, Object> def = new HashMap<>();
def.put("engine", "javascript");
def.put("debug", false);
def.put("github_script_downloads", false);
return def;
}
protected int reloadScripts() {
scripts.forEach(s -> {
s.saveData();
s.cleanup();
});
scripts.clear();
config.reload();
return config.loadPlaceholders();
}
public static JavascriptExpansion getInstance() {
return instance;
}
public GithubScriptManager getGithubScriptManager() {
return githubScripts;
}
private boolean unregisterCommand() {
if (commandMap == null || commands == null) return false;
return commands.unregister(commandMap);
}
private boolean registerCommand() {
if (commandMap == null) return false;
commands = new JavascriptExpansionCommands(this);
commandMap.register("papi" + commands.getName(), commands);
return commands.isRegistered();
}
}

View File

@ -22,132 +22,167 @@ package com.extendedclip.papi.expansion.javascript;
import com.extendedclip.papi.expansion.javascript.cloud.GithubScript;
import com.extendedclip.papi.expansion.javascript.cloud.GithubScriptManager;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class JavascriptExpansionCommands extends Command {
private JavascriptExpansion expansion;
private JavascriptExpansion expansion;
private final String PERMISSION = "placeholderapi.js.admin";
private String command;
public JavascriptExpansionCommands(JavascriptExpansion expansion) {
super("jsexpansion");
this.expansion = expansion;
this.setDescription("Javascript expansion commands");
this.setUsage("/jsexpansion <arg>");
this.setPermission("placeholderapi.js.admin");
}
@Override
public boolean execute(CommandSender s, String label, String[] args) {
if (!s.hasPermission(this.getPermission())) {
msg(s, "&cYou don't have permission to do that!");
return true;
public JavascriptExpansionCommands(JavascriptExpansion expansion) {
super("jsexpansion");
command = getName();
this.expansion = expansion;
this.setDescription("Javascript expansion commands");
this.setUsage("/" + command + " <args>");
this.setPermission(PERMISSION);
}
if (args.length == 0) {
msg(s, "&eJavascript expansion &7v: &f" + expansion.getVersion(),
"&eCreated by: &f" + expansion.getAuthor(),
"&eWiki: &ahttps://github.com/PlaceholderAPI-Expansions/Javascript-Expansion/wiki",
"&r",
"&e/jsexpansion reload &7- &fReload your javascripts without reloading PlaceholderAPI",
"&e/jsexpansion list &7- &fList loaded script identifiers.");
if (expansion.getGithubScriptManager() != null) {
msg(s, "&e&e/jsexpansion git refresh &7- &fRefresh available Github scripts",
"&e/jsexpansion git download <name> &7- &fDownload a script from the js expansion github.",
"&e/jsexpansion git list &7- &fList available scripts in the js expansion github.",
"&e/jsexpansion git info (name) &7- &fGet the description and url of a specific script.");
}
return true;
}
if (args[0].equalsIgnoreCase("reload")) {
msg(s, "&aJavascriptExpansion reloading...");
int l = expansion.reloadScripts();
msg(s, l + " &7script" + (l == 1 ? "" : "s") + " loaded");
return true;
}
if (args[0].equalsIgnoreCase("list")) {
List<String> loaded = expansion.getLoadedIdentifiers();
msg(s, loaded.size() + " &7script" + (loaded.size() == 1 ? "" : "s") + " loaded");
msg(s, String.join(", ", loaded));
return true;
}
if (args[0].equalsIgnoreCase("git")) {
if (expansion.getGithubScriptManager() == null) {
msg(s, "&8This feature is disabled in the PlaceholderAPI config.");
return true;
}
if (args.length < 2) {
msg(s, "&cIncorrect usage!");
return true;
}
GithubScriptManager manager = expansion.getGithubScriptManager();
if (args[1].equalsIgnoreCase("refresh")) {
expansion.getGithubScriptManager().fetch();
msg(s, "&aFetching available scripts... Check back in a sec!");
return true;
}
if (args[1].equalsIgnoreCase("list")) {
msg(s, manager.getAvailableScripts().size() + " &escript"
+ (manager.getAvailableScripts().size() == 1 ? "" : "s") + " available on Github.",
String.join(", ", manager.getAvailableScripts().stream()
.map(GithubScript::getName)
.collect(Collectors.toSet())));
return true;
}
if (args[1].equalsIgnoreCase("info")) {
if (args.length < 3) {
msg(s, "&4Incorrect usage! &f" + this.getName() + " git info <name>");
return true;
}
GithubScript script = manager.getScript(args[2]);
if (script == null) {
msg(s, "&4The script &f" + args[2] + " &4does not exist!");
return true;
}
msg(s, "&eName: &f" + script.getName(),
"&eVersion: &f" + script.getVersion(),
"&eDescription: &f" + script.getDescription(),
"&eAuthor: &f" + script.getAuthor(),
"&eSource URL: &f" + script.getUrl());
return true;
}
if (args[1].equalsIgnoreCase("download")) {
if (args.length < 3) {
msg(s, "&4Incorrect usage! &f" + this.getName() + " git download <name>");
return true;
}
GithubScript script = manager.getScript(args[2]);
if (script == null) {
msg(s, "&4The script &f" + args[2] + " &4does not exist!");
return true;
@Override
public boolean execute(CommandSender sender, String label, String[] args) {
if (!sender.hasPermission(PERMISSION)) {
msg(sender, "&cYou don't have permission to do that!");
return true;
}
manager.downloadScript(script);
msg(s, "&aDownload started... &eCheck the scripts folder in a moment...");
return true;
}
msg(s, "&4Incorrect usage! &f" + this.getName() + " &7for more help.");
return true;
if (args.length == 0) {
msg(sender,
"&eJavascript expansion &7v: &f" + expansion.getVersion(),
"&eCreated by: &f" + expansion.getAuthor(),
"&eWiki: &fhttps://github.com/PlaceholderAPI-Expansions/Javascript-Expansion/wiki",
"&r",
"&e/" + command + " reload &7- &fReload your javascripts without reloading PlaceholderAPI",
"&e/" + command + " list &7- &fList loaded script identifiers."
);
if (expansion.getGithubScriptManager() != null) {
msg(sender,
"&e&e/" + command + " git refresh &7- &fRefresh available Github scripts",
"&e/" + command + " git download <name> &7- &fDownload a script from the js expansion github.",
"&e/" + command + " git list &7- &fList available scripts in the js expansion github.",
"&e/" + command + " git info (name) &7- &fGet the description and url of a specific script."
);
}
return true;
}
switch (args[0].toLowerCase()) {
case "reload": {
msg(sender, "&aJavascriptExpansion reloading...");
final int scripts = expansion.reloadScripts();
msg(sender, scripts + " &7script" + plural(scripts) + " loaded");
return true;
}
case "list": {
final List<String> loaded = expansion.getLoadedIdentifiers();
msg(sender,
loaded.size() + " &7script" + plural(loaded.size()) + " loaded.",
String.join(", ", loaded)
);
return true;
}
case "git": {
if (expansion.getGithubScriptManager() == null) {
msg(sender, "&8This feature is disabled in the PlaceholderAPI config.");
return true;
}
if (args.length < 2) {
msg(sender, "&cIncorrect usage!");
return true;
}
final GithubScriptManager manager = expansion.getGithubScriptManager();
switch (args[1].toLowerCase()) {
case "refresh": {
expansion.getGithubScriptManager().fetch();
msg(sender, "&aFetching available scripts... Check back in a sec!");
return true;
}
case "list": {
final List<GithubScript> availableScripts = manager.getAvailableScripts();
final Set<String> scripts = availableScripts.stream().map(GithubScript::getName).collect(Collectors.toSet());
msg(sender, availableScripts.size() + " &escript" + plural(availableScripts.size()) + " available on Github.", String.join(", ", scripts));
return true;
}
case "info": {
if (args.length < 3) {
msg(sender, "&4Incorrect usage! &f/" + command + " git info <name>");
return true;
}
final GithubScript script = manager.getScript(args[2]);
if (script == null) {
msg(sender, "&4The script &f" + args[2] + " &4does not exist!");
return true;
}
msg(sender,
"&eName: &f" + script.getName(),
"&eVersion: &f" + script.getVersion(),
"&eDescription: &f" + script.getDescription(),
"&eAuthor: &f" + script.getAuthor(),
"&eSource URL: &f" + script.getUrl()
);
return true;
}
case "download": {
if (args.length < 3) {
msg(sender, "&4Incorrect usage! &f/" + command + " git download <name>");
return true;
}
final GithubScript script = manager.getScript(args[2]);
if (script == null) {
msg(sender, "&4The script &f" + args[2] + " &4does not exist!");
return true;
}
manager.downloadScript(script);
msg(sender, "&6Download started... &eCheck the scripts folder in a moment...");
return true;
}
default: {
msg(sender, "&4Incorrect usage! &f/" + command + " &7for more help.");
return true;
}
}
}
default: {
return true;
}
}
}
return true;
}
private String plural(final int amount) {
return amount > 1 ? "s" : "";
}
public void msg(CommandSender s, String... text) {
Arrays.stream(text)
.forEach(line -> s.sendMessage(ChatColor.translateAlternateColorCodes('&', line)));
}
public void msg(CommandSender sender, String... text) {
if (text == null) {
return;
}
Arrays.stream(text).forEach(line -> sender.sendMessage(ChatColor.translateAlternateColorCodes('&', line)));
}
}

View File

@ -20,11 +20,6 @@
*/
package com.extendedclip.papi.expansion.javascript;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import me.clip.placeholderapi.PlaceholderAPI;
import me.clip.placeholderapi.PlaceholderAPIPlugin;
import org.apache.commons.lang.Validate;
@ -34,165 +29,161 @@ import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.File;
import java.io.IOException;
import java.util.Set;
public class JavascriptPlaceholder {
private final String FILEDIR =
PlaceholderAPIPlugin.getInstance().getDataFolder() + File.separator + "javascripts"
+ File.separator + "javascript_data";
private ScriptEngine engine = null;
private String identifier;
private String script;
private ScriptData data = null;
private File dataFile;
private FileConfiguration cfg;
private final String DIRECTORY = PlaceholderAPIPlugin.getInstance().getDataFolder() + "/javascripts/javascript_data";
private ScriptEngine engine;
private String identifier;
private String script;
private ScriptData data;
private File dataFile;
private FileConfiguration config;
public JavascriptPlaceholder(ScriptEngine engine, String identifier, String script) {
Validate.notNull(engine, "ScriptEngine can not be null");
Validate.notNull(identifier, "Identifier can not be null");
Validate.notNull(script, "script can not be null");
this.engine = engine;
this.identifier = identifier;
this.script = script;
File dir = new File(FILEDIR);
public JavascriptPlaceholder(ScriptEngine engine, String identifier, String script) {
Validate.notNull(engine, "ScriptEngine can not be null");
Validate.notNull(identifier, "Identifier can not be null");
Validate.notNull(script, "Script can not be null");
try {
if (!dir.exists()) {
dir.mkdirs();
}
} catch (SecurityException e) {
e.printStackTrace();
}
data = new ScriptData();
dataFile = new File(FILEDIR, identifier + "_data.yml");
engine.put("Data", data);
engine.put("BukkitServer", Bukkit.getServer());
engine.put("Expansion", JavascriptExpansion.getInstance());
engine.put("Placeholder", this);
}
this.engine = engine;
this.identifier = identifier;
this.script = script;
final File directory = new File(DIRECTORY);
public String getIdentifier() {
return identifier;
}
public String getScript() {
return script;
}
public String evaluate(OfflinePlayer p, String... args) {
String exp = PlaceholderAPI.setPlaceholders(p, script);
try {
String[] c = null;
if (args != null && args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (args[i] == null || args[i].isEmpty()) {
continue;
}
String s = PlaceholderAPI.setBracketPlaceholders(p, args[i]);
if (c == null) {
c = new String[args.length];
}
c[i] = s;
if (directory.exists()) {
directory.mkdirs();
}
}
if (c == null) {
c = new String[]{};
}
engine.put("args", c);
engine.put("BukkitPlayer", p != null && p.isOnline() ? p.getPlayer() : null);
engine.put("OfflinePlayer", p);
Object result = engine.eval(exp);
return result != null ? PlaceholderAPI.setBracketPlaceholders(p, result.toString()) : "";
} catch (ScriptException ex) {
ex.printStackTrace();
}
return "Script error";
}
public ScriptData getData() {
// this should never be null but just in case setData(null) is called
if (data == null) {
data = new ScriptData();
}
return data;
}
public void setData(ScriptData data) {
this.data = data;
}
public boolean loadData() {
cfg = new YamlConfiguration();
if (!dataFile.exists()) {
return false;
}
try {
cfg.load(dataFile);
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (InvalidConfigurationException e) {
e.printStackTrace();
return false;
data = new ScriptData();
dataFile = new File(DIRECTORY, identifier + "_data.yml");
engine.put("Data", data);
engine.put("BukkitServer", Bukkit.getServer());
engine.put("Expansion", JavascriptExpansion.getInstance());
engine.put("Placeholder", this);
engine.put("PlaceholderAPI", PlaceholderAPI.class);
}
final Set<String> keys = cfg.getKeys(true);
if (keys == null || keys.isEmpty()) {
return false;
public String getIdentifier() {
return identifier;
}
if (data == null) {
data = new ScriptData();
} else {
data.clear();
public String getScript() {
return script;
}
keys.stream().forEach(k -> {
data.set(k, cfg.get(k));
});
public String evaluate(OfflinePlayer player, String... args) {
String exp = PlaceholderAPI.setPlaceholders(player, script);
if (!data.isEmpty()) {
this.setData(data);
return true;
}
return false;
}
try {
String[] arguments = null;
public boolean saveData() {
if (data == null || data.isEmpty()) {
return false;
if (args != null && args.length > 0) {
arguments = new String[args.length];
for (int i = 0; i < args.length; i++) {
if (args[i] == null || args[i].isEmpty()) {
continue;
}
arguments[i] = PlaceholderAPI.setBracketPlaceholders(player, args[i]);
}
}
if (arguments == null) {
arguments = new String[]{};
}
engine.put("args", arguments);
engine.put("BukkitPlayer", player != null && player.isOnline() ? player.getPlayer() : null);
engine.put("OfflinePlayer", player);
Object result = engine.eval(exp);
return result != null ? PlaceholderAPI.setBracketPlaceholders(player, result.toString()) : "";
} catch (ScriptException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
return "Script error";
}
if (cfg == null) {
return false;
public ScriptData getData() {
// this should never be null but just in case setData(null) is called
if (data == null) {
data = new ScriptData();
}
return data;
}
data.getData().entrySet().forEach(e -> {
cfg.set(e.getKey(), e.getValue());
});
try {
cfg.save(dataFile);
return true;
} catch (IOException e) {
return false;
public void setData(ScriptData data) {
this.data = data;
}
}
public void cleanup() {
if (this.data != null) {
this.data.clear();
this.data = null;
public boolean loadData() {
config = new YamlConfiguration();
if (!dataFile.exists()) {
return false;
}
try {
config.load(dataFile);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
return false;
}
final Set<String> keys = config.getKeys(true);
if (keys.size() == 0) {
return false;
}
if (data == null) {
data = new ScriptData();
} else {
data.clear();
}
keys.forEach(key -> data.set(key, config.get(key)));
if (!data.isEmpty()) {
this.setData(data);
return true;
}
return false;
}
public boolean saveData() {
if (data == null || data.isEmpty()) {
return false;
}
if (config == null) {
return false;
}
data.getData().forEach((key, value) -> config.set(key, value));
try {
config.save(dataFile);
return true;
} catch (IOException e) {
return false;
}
}
public void cleanup() {
if (this.data != null) {
this.data.clear();
this.data = null;
}
this.config = null;
}
this.cfg = null;
}
}

View File

@ -20,214 +20,202 @@
*/
package com.extendedclip.papi.expansion.javascript;
import me.clip.placeholderapi.PlaceholderAPIPlugin;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import me.clip.placeholderapi.PlaceholderAPIPlugin;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
public class JavascriptPlaceholdersConfig {
private JavascriptExpansion ex;
private JavascriptExpansion ex;
private PlaceholderAPIPlugin plugin;
private PlaceholderAPIPlugin plugin;
private FileConfiguration config;
private FileConfiguration config;
private File file;
private File file;
public JavascriptPlaceholdersConfig(JavascriptExpansion ex) {
this.ex = ex;
plugin = ex.getPlaceholderAPI();
reload();
}
public void reload() {
if (file == null) {
file = new File(plugin.getDataFolder(), "javascript_placeholders.yml");
public JavascriptPlaceholdersConfig(JavascriptExpansion ex) {
this.ex = ex;
plugin = ex.getPlaceholderAPI();
reload();
}
config = YamlConfiguration.loadConfiguration(file);
config.options().header("Javascript Expansion: " + ex.getVersion()
+ "\nThis is the main configuration file for the Javascript Expansion."
+ "\n"
+ "\nYou will define your javascript placeholders in this file."
+ "\n"
+ "\nJavascript files must be located in the:"
+ "\n /plugins/placeholderapi/javascripts/ folder"
+ "\n"
+ "\nA detailed guide on how to create your own javascript placeholders"
+ "\ncan be found here:"
+ "\nhttps://github.com/PlaceholderAPI-Expansions/Javascript-Expansion/wiki"
+ "\n"
+ "\nYour javascript placeholders will be identified by: %javascript_<identifier>%"
+ "\n"
+ "\nConfiguration format:"
+ "\n"
+ "\n<identifier>:"
+ "\n file: <name of file>.<file extension>"
+ "\n engine: (name of script engine)"
+ "\n"
+ "\n"
+ "\nExample:"
+ "\n"
+ "\n'my_placeholder':"
+ "\n file: 'my_placeholder.js'"
+ "\n engine: 'nashorn'");
public void reload() {
if (file == null) {
file = new File(plugin.getDataFolder(), "javascript_placeholders.yml");
}
if (config.getKeys(false) == null || config.getKeys(false).isEmpty()) {
config.set("example.file", "example.js");
config.set("example.engine", "nashorn");
}
save();
}
config = YamlConfiguration.loadConfiguration(file);
config.options().header("Javascript Expansion: " + ex.getVersion()
+ "\nThis is the main configuration file for the Javascript Expansion."
+ "\n"
+ "\nYou will define your javascript placeholders in this file."
+ "\n"
+ "\nJavascript files must be located in the:"
+ "\n /plugins/placeholderapi/javascripts/ folder"
+ "\n"
+ "\nA detailed guide on how to create your own javascript placeholders"
+ "\ncan be found here:"
+ "\nhttps://github.com/PlaceholderAPI-Expansions/Javascript-Expansion/wiki"
+ "\n"
+ "\nYour javascript placeholders will be identified by: %javascript_<identifier>%"
+ "\n"
+ "\nConfiguration format:"
+ "\n"
+ "\n<identifier>:"
+ "\n file: <name of file>.<file extension>"
+ "\n engine: (name of script engine)"
+ "\n"
+ "\n"
+ "\nExample:"
+ "\n"
+ "\n'my_placeholder':"
+ "\n file: 'my_placeholder.js'"
+ "\n engine: 'nashorn'");
public FileConfiguration load() {
if (config == null) {
reload();
}
return config;
}
if (config.getKeys(false).isEmpty()) {
config.set("example.file", "example.js");
config.set("example.engine", "nashorn");
}
public void save() {
if ((config == null) || (file == null)) {
return;
save();
}
try {
load().save(file);
} catch (IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Could not save to " + file, ex);
}
}
public int loadPlaceholders() {
if (config == null || config.getKeys(false) == null || config.getKeys(false).isEmpty()) {
return 0;
public FileConfiguration load() {
if (config == null) {
reload();
}
return config;
}
File dir = new File(plugin.getDataFolder() + File.separator + "javascripts");
try {
if (!dir.exists()) {
dir.mkdirs();
plugin.getLogger().info(
"Creating directory: plugins" + File.separator + "PlaceholderAPI" + File.separator
+ "javascripts");
} else {
}
} catch (SecurityException e) {
plugin.getLogger().severe(
"Could not create directory: plugins" + File.separator + "PlaceholderAPI" + File.separator
+ "javascripts");
}
for (String identifier : config.getKeys(false)) {
if (!config.contains(identifier + ".file")
|| config.getString(identifier + ".file", null) == null) {
plugin.getLogger()
.warning("Javascript placeholder: " + identifier + " does not have a file specified");
continue;
}
File scriptFile = new File(plugin.getDataFolder() + File.separator + "javascripts",
config.getString(identifier + ".file"));
if (!scriptFile.exists()) {
plugin.getLogger().info(scriptFile.getName() + " does not exist. Creating file...");
public void save() {
if ((config == null) || (file == null)) {
return;
}
try {
scriptFile.createNewFile();
plugin.getLogger().info(scriptFile.getName()
+ " created! Add your javascript to this file and use /placeholderapi reload to load it!");
} catch (IOException e) {
e.printStackTrace();
load().save(file);
} catch (IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Could not save to " + file, ex);
}
continue;
}
}
String script = getContents(scriptFile);
public int loadPlaceholders() {
if (config == null || config.getKeys(false).isEmpty()) {
return 0;
}
if (script == null || script.isEmpty()) {
plugin.getLogger().warning(
"File: " + scriptFile.getName() + " for javascript placeholder: " + identifier
+ " is empty");
continue;
}
File dir = new File(plugin.getDataFolder() + File.separator + "javascripts");
ScriptEngine engine = null;
if (!config.contains(identifier + ".engine")) {
engine = ex.getGlobalEngine();
} else {
try {
engine = new ScriptEngineManager()
.getEngineByName(config.getString(identifier + ".engine", "nashorn"));
} catch (NullPointerException e) {
plugin.getLogger().warning("ScriptEngine type for javascript placeholder: " + identifier
+ " is invalid! Defaulting to global");
engine = ex.getGlobalEngine();
if (!dir.exists()) {
dir.mkdirs();
plugin.getLogger().info("Creating directory: plugins/PlaceholderAPI/javascripts");
}
} catch (SecurityException e) {
plugin.getLogger().severe("Could not create directory: plugins/PlaceholderAPI/javascripts");
}
}
if (engine == null) {
plugin.getLogger()
.warning("Failed to set ScriptEngine for javascript placeholder: " + identifier);
continue;
}
for (String identifier : config.getKeys(false)) {
if (!config.contains(identifier + ".file") || config.getString(identifier + ".file") == null) {
plugin.getLogger().warning("Javascript placeholder: " + identifier + " does not have a file specified");
continue;
}
JavascriptPlaceholder pl = new JavascriptPlaceholder(engine, identifier, script);
File scriptFile = new File(plugin.getDataFolder() + "/javascripts", config.getString(identifier + ".file"));
boolean added = ex.addJSPlaceholder(pl);
if (!scriptFile.exists()) {
plugin.getLogger().info(scriptFile.getName() + " does not exist. Creating file...");
if (added) {
try {
scriptFile.createNewFile();
plugin.getLogger().info(scriptFile.getName()
+ " created! Add your javascript to this file and use /placeholderapi reload to load it!");
} catch (IOException e) {
e.printStackTrace();
}
continue;
}
if (pl.loadData()) {
plugin.getLogger().info("Loaded data for javascript placeholder: " + identifier);
String script = getContents(scriptFile);
if (script == null || script.isEmpty()) {
plugin.getLogger().warning("File: " + scriptFile.getName() + " for javascript placeholder: " + identifier + " is empty");
continue;
}
ScriptEngine engine;
if (!config.contains(identifier + ".engine")) {
engine = ex.getGlobalEngine();
} else {
try {
engine = new ScriptEngineManager().getEngineByName(config.getString(identifier + ".engine", "nashorn"));
} catch (NullPointerException e) {
plugin.getLogger().warning("ScriptEngine type for javascript placeholder: " + identifier + " is invalid! Defaulting to global");
engine = ex.getGlobalEngine();
}
}
if (engine == null) {
plugin.getLogger().warning("Failed to set ScriptEngine for javascript placeholder: " + identifier);
continue;
}
final JavascriptPlaceholder pl = new JavascriptPlaceholder(engine, identifier, script);
final boolean added = ex.addJSPlaceholder(pl);
if (added) {
if (pl.loadData()) {
plugin.getLogger().info("Loaded data for javascript placeholder: " + identifier);
}
plugin.getLogger().info("%javascript_" + identifier + "% has been loaded!");
} else {
plugin.getLogger().warning("Javascript placeholder %javascript_" + identifier + "% is a duplicate!");
}
}
plugin.getLogger().info("%javascript_" + identifier + "% has been loaded!");
} else {
plugin.getLogger()
.warning("Javascript placeholder %javascript_" + identifier + "% is a duplicate!");
}
return ex.getAmountLoaded();
}
return ex.getAmountLoaded();
}
private String getContents(File f) {
StringBuilder sb = new StringBuilder();
private String getContents(File file) {
final StringBuilder sb = new StringBuilder();
try {
Scanner scanner = new Scanner(f);
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line == null || line.isEmpty()) {
continue;
if (line == null || line.isEmpty()) {
continue;
}
line = line.trim();
/* temp fix for single line comments
* doesnt solve every case though..
* lines that start with code and may have a comment afterward still screw stuff up...
*/
if (line.startsWith("//")) {
continue;
}
sb.append(line).append(" ");
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
line = line.trim();
/* temp fix for single line comments
* doesnt solve every case though..
* lines that start with code and may have a comment afterward still screw stuff up...
*/
if (line.startsWith("//")) {
continue;
}
sb.append(line + " ");
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
return sb.toString();
}
return sb.toString();
}
}

View File

@ -25,41 +25,41 @@ import java.util.Map;
public class ScriptData {
private Map<String, Object> map;
private Map<String, Object> map;
public ScriptData(Map<String, Object> data) {
this.map = data;
}
public ScriptData(Map<String, Object> data) {
this.map = data;
}
public ScriptData() {
this.map = new HashMap<>();
}
public ScriptData() {
this.map = new HashMap<>();
}
public Map<String, Object> getData() {
return map;
}
public Map<String, Object> getData() {
return map;
}
public void clear() {
map.clear();
}
public void clear() {
map.clear();
}
public boolean exists(String key) {
return map.containsKey(key) && map.get(key) != null;
}
public boolean exists(String key) {
return map.containsKey(key) && map.get(key) != null;
}
public Object get(String key) {
return map.get(key);
}
public Object get(String key) {
return map.get(key);
}
public void remove(String key) {
map.put(key, null);
}
public void remove(String key) {
map.put(key, null);
}
public void set(String key, Object value) {
map.put(key, value);
}
public void set(String key, Object value) {
map.put(key, value);
}
public boolean isEmpty() {
return map.isEmpty();
}
public boolean isEmpty() {
return map.isEmpty();
}
}

View File

@ -22,33 +22,33 @@ package com.extendedclip.papi.expansion.javascript.cloud;
public class GithubScript {
private String name, version, author, description, url;
private String name, version, author, description, url;
public GithubScript(String name, String version, String author, String description, String url) {
this.name = name;
this.version = version;
this.author = author;
this.description = description;
this.url = url;
}
public GithubScript(String name, String version, String author, String description, String url) {
this.name = name;
this.version = version;
this.author = author;
this.description = description;
this.url = url;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public String getVersion() {
return version;
}
public String getAuthor() {
return author;
}
public String getAuthor() {
return author;
}
public String getDescription() {
return description;
}
public String getDescription() {
return description;
}
public String getUrl() {
return url;
}
public String getUrl() {
return url;
}
}

View File

@ -23,105 +23,103 @@ package com.extendedclip.papi.expansion.javascript.cloud;
import com.extendedclip.papi.expansion.javascript.JavascriptExpansion;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import org.bukkit.Bukkit;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
public class GithubScriptManager {
private JavascriptExpansion expansion;
private String javascriptsFolder;
private List<GithubScript> availableScripts;
private final String MASTER_LIST_URL = "https://raw.githubusercontent.com/PlaceholderAPI/Javascript-Expansion/master/scripts/master_list.json";
private final Gson GSON = new Gson();
private JavascriptExpansion expansion;
private String javascriptsFolder;
private List<GithubScript> availableScripts;
private final String MASTER_LIST_URL = "https://raw.githubusercontent.com/PlaceholderAPI/Javascript-Expansion/master/scripts/master_list.json";
private final Gson GSON = new Gson();
public GithubScriptManager(JavascriptExpansion expansion) {
this.expansion = expansion;
javascriptsFolder = expansion.getPlaceholderAPI().getDataFolder()
+ File.separator
+ "javascripts"
+ File.separator;
}
public void clear() {
availableScripts = null;
}
public void fetch() {
Bukkit.getScheduler().runTaskAsynchronously(expansion.getPlaceholderAPI(), new Runnable() {
@Override
public void run() {
String json = getContents(MASTER_LIST_URL);
if (json.isEmpty()) {
return;
}
availableScripts = GSON.fromJson(json, new TypeToken<ArrayList<GithubScript>>() {
}.getType());
}
});
}
public void downloadScript(GithubScript script) {
Bukkit.getScheduler().runTaskAsynchronously(expansion.getPlaceholderAPI(), new Runnable() {
@Override
public void run() {
List<String> contents = read(script.getUrl());
if (contents == null || contents.isEmpty()) {
return;
}
File f = new File(javascriptsFolder, script.getName() + ".js");
try (PrintStream out = new PrintStream(new FileOutputStream(f))) {
contents.forEach(l -> out.println(l));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
Bukkit.getScheduler().runTask(expansion.getPlaceholderAPI(), new Runnable() {
@Override
public void run() {
expansion.getConfig().load().set(script.getName() + ".file", script.getName() + ".js");
expansion.getConfig().save();
}
});
}
});
}
private String getContents(String url) {
return String.join("", read(url));
}
private List<String> read(String url) {
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new URL(url).openStream()))) {
String inputLine;
while ((inputLine = reader.readLine()) != null) {
lines.add(inputLine);
}
} catch (Exception ex) {
ex.printStackTrace();
public GithubScriptManager(JavascriptExpansion expansion) {
this.expansion = expansion;
javascriptsFolder = expansion.getPlaceholderAPI().getDataFolder()
+ File.separator
+ "javascripts"
+ File.separator;
}
return lines;
}
public void clear() {
availableScripts = null;
}
public List<GithubScript> getAvailableScripts() {
return availableScripts;
}
public void fetch() {
Bukkit.getScheduler().runTaskAsynchronously(expansion.getPlaceholderAPI(), new Runnable() {
@Override
public void run() {
String json = getContents(MASTER_LIST_URL);
if (json.isEmpty()) {
return;
}
availableScripts = GSON.fromJson(json, new TypeToken<ArrayList<GithubScript>>() {
}.getType());
}
});
}
public GithubScript getScript(String name) {
if (availableScripts == null) return null;
return availableScripts.stream().filter(s -> {return s.getName().equalsIgnoreCase(name);}).findFirst().orElse(null);
}
public void downloadScript(GithubScript script) {
Bukkit.getScheduler().runTaskAsynchronously(expansion.getPlaceholderAPI(), new Runnable() {
@Override
public void run() {
List<String> contents = read(script.getUrl());
if (contents == null || contents.isEmpty()) {
return;
}
File f = new File(javascriptsFolder, script.getName() + ".js");
try (PrintStream out = new PrintStream(new FileOutputStream(f))) {
contents.forEach(l -> out.println(l));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
Bukkit.getScheduler().runTask(expansion.getPlaceholderAPI(), new Runnable() {
@Override
public void run() {
expansion.getConfig().load().set(script.getName() + ".file", script.getName() + ".js");
expansion.getConfig().save();
}
});
}
});
}
private String getContents(String url) {
return String.join("", read(url));
}
private List<String> read(String url) {
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new URL(url).openStream()))) {
String inputLine;
while ((inputLine = reader.readLine()) != null) {
lines.add(inputLine);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return lines;
}
public List<GithubScript> getAvailableScripts() {
return availableScripts;
}
public GithubScript getScript(String name) {
if (availableScripts == null) return null;
return availableScripts.stream().filter(s -> {
return s.getName().equalsIgnoreCase(name);
}).findFirst().orElse(null);
}
}