Plugin updater refactored, player data needs a default on declaration now, color codes added #35

Merged
NorbiPeti merged 5 commits from dev into master 2017-07-03 21:58:11 +00:00
11 changed files with 277 additions and 175 deletions

View file

@ -36,8 +36,9 @@ public class MainPlugin extends JavaPlugin {
TBMCCoreAPI.RegisterEventsForExceptions(new PlayerListener(), this);
TBMCCoreAPI.RegisterUserClass(TBMCPlayerBase.class);
TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fg§f", Color.White, "g", null));
TBMCChatAPI.RegisterChatChannel(
Channel.AdminChat = new Channel("§cADMIN§f", Color.Red, "a", s -> s.isOp() ? new RecipientTestResult(0)
TBMCChatAPI.RegisterChatChannel(Channel.AdminChat = new Channel("§cADMIN§f", Color.Red, "a",
s -> s.isOp() //
? new RecipientTestResult(0)
: new RecipientTestResult("You need to be an admin to use this channel.")));
TBMCChatAPI.RegisterChatChannel(Channel.ModChat = new Channel("§9MOD§f", Color.Blue, "mod",
s -> s.isOp() || (s instanceof Player && MainPlugin.permission.playerInGroup((Player) s, "mod"))

View file

@ -3,6 +3,7 @@ package buttondevteam.core;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import buttondevteam.lib.PluginUpdater;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.TBMCCommandBase;
@ -14,7 +15,7 @@ public class UpdatePluginCommand extends TBMCCommandBase {
if (args.length == 0) {
sender.sendMessage("Downloading plugin names...");
boolean first = true;
for (String plugin : TBMCCoreAPI.GetPluginNames()) {
for (String plugin : PluginUpdater.GetPluginNames()) {
if (first) {
sender.sendMessage("§6---- Plugin names ----");
first = false;

View file

@ -0,0 +1,195 @@
package buttondevteam.lib;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class PluginUpdater {
private PluginUpdater() {
}
/**
* See {@link TBMCCoreAPI#UpdatePlugin(String, CommandSender, String)}
*/
public static boolean UpdatePlugin(String name, CommandSender sender, String branch) {
info(sender, "Checking plugin name...");
List<String> plugins = GetPluginNames();
String correctname = null;
for (String plugin : plugins) {
if (plugin.equalsIgnoreCase(name)) {
correctname = plugin; // Fixes capitalization
break;
}
}
if (correctname == null) {
error(sender, "Can't find plugin: " + name);
return false;
}
info(sender, "Checking branch name...");
if (!TBMCCoreAPI.IsTestServer() && !branch.equalsIgnoreCase("master")) {
error(sender, "The server is in production mode, updating only allowed from master!");
return false;
}
Optional<String> correctbranch = GetPluginBranches(correctname).stream().filter(b -> b.equalsIgnoreCase(branch))
.findAny();
if (!correctbranch.isPresent()) {
error(sender, "Can't find branch \"" + branch + "\" for plugin \"" + correctname + "\"");
return false;
}
if (!isMaven(correctname, correctbranch.get())) {
error(sender, "The plugin doesn't appear to have a pom.xml. Make sure it's a Maven project.");
return false;
}
info(sender, "Updating TBMC plugin: " + correctname + " from " + correctbranch.get());
return updatePluginJitPack(sender, correctname, correctbranch);
}
private static boolean updatePluginJitPack(CommandSender sender, String correctname,
Optional<String> correctbranch) {
URL url;
final boolean isWindows = System.getProperty("os.name").contains("Windows");
File result = new File("plugins/" + correctname + (isWindows ? ".jar" : ".jar_tmp"));
File finalresult = new File("plugins/" + correctname + ".jar");
try {
url = new URL("https://jitpack.io/com/github/TBMCPlugins/"
+ (correctname.equals("ButtonCore") ? "ButtonCore/ButtonCore" : correctname) + "/"
+ correctbranch.get() + "-SNAPSHOT/" + correctname + "-" + correctbranch.get() + "-SNAPSHOT.jar"); // ButtonCore exception required since it hosts Towny as well
FileUtils.copyURLToFile(url, result);
if (!result.exists() || result.length() < 25) {
result.delete();
error(sender, "The downloaded JAR for " + correctname + " from " + correctbranch.get()
+ " is too small (smnaller than 25 bytes). Am I downloading from the right place?");
return false;
} else {
if (!isWindows)
Files.move(result.toPath(), finalresult.toPath(), StandardCopyOption.REPLACE_EXISTING);
info(sender, "Updating plugin " + correctname + " from " + correctbranch.get() + " done!");
return true;
}
} catch (FileNotFoundException e) {
error(sender,
"Can't find JAR for " + correctname + " from " + correctbranch.get()
+ ", the build probably failed. Build log (scroll to bottom):" + "\n"
+ "https://jitpack.io/com/github/TBMCPlugins/" + correctname + "/" + correctbranch.get()
+ "-SNAPSHOT/build.log\nIf you'd like to rebuild the same commit, go to:\nhttps://jitpack.io/#TBMCPlugins/"
+ correctname + "\nAnd delete the newest build.");
} catch (IOException e) {
error(sender, "IO error while updating " + correctname + "\n" + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
error(sender, "Unknown error while updating " + correctname + ": " + e);
}
return false;
}
/**
* Checks if pom.xml is present for the project.
*
* @param pluginname
* Does not have to match case
* @param branch
* Does not have to match case
*/
public static boolean isMaven(String pluginname, String branch) {
try {
return !TBMCCoreAPI
.DownloadString(
"https://raw.githubusercontent.com/TBMCPlugins/" + pluginname + "/" + branch + "/pom.xml")
.equals("404: Not Found\n");
} catch (IOException e1) {
return false;
}
}
private static void error(CommandSender sender, String message) {
if (!sender.equals(Bukkit.getConsoleSender()))
Bukkit.getLogger().warning(message);
sender.sendMessage("§c" + message);
}
private static void info(CommandSender sender, String message) {
if (!sender.equals(Bukkit.getConsoleSender()))
Bukkit.getLogger().info(message);
sender.sendMessage("§b" + message);
}
/**
* Retrieves all the repository names from the GitHub organization.
*
* @return A list of names
*/
public static List<String> GetPluginNames() {
List<String> ret = new ArrayList<>();
try {
String resp = TBMCCoreAPI.DownloadString("https://api.github.com/orgs/TBMCPlugins/repos");
JsonArray arr = new JsonParser().parse(resp).getAsJsonArray();
for (JsonElement obj : arr) {
JsonObject jobj = obj.getAsJsonObject();
ret.add(jobj.get("name").getAsString());
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
/**
* Retrieves all the branches from the plugin repository.
*
* @return A list of names
*/
public static List<String> GetPluginBranches(String plugin) {
List<String> ret = new ArrayList<>();
try {
String resp = TBMCCoreAPI
.DownloadString("https://api.github.com/repos/TBMCPlugins/" + plugin + "/branches");
JsonArray arr = new JsonParser().parse(resp).getAsJsonArray();
for (JsonElement obj : arr) {
JsonObject jobj = obj.getAsJsonObject();
ret.add(jobj.get("name").getAsString());
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
public static class UpdatedEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private JsonObject data;
public UpdatedEvent(JsonObject data) {
this.data = data;
}
public JsonObject getData() {
return data;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
}

View file

@ -2,12 +2,9 @@ package buttondevteam.lib;
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.Map.Entry;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
@ -15,8 +12,6 @@ import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import com.google.gson.*;
import buttondevteam.core.MainPlugin;
import buttondevteam.lib.player.ChromaGamerBase;
import buttondevteam.lib.potato.DebugPotato;
@ -57,127 +52,7 @@ public class TBMCCoreAPI {
* @return Success or not
*/
public static boolean UpdatePlugin(String name, CommandSender sender, String branch) {
info(sender, "Checking plugin name...");
List<String> plugins = GetPluginNames();
String correctname = null;
for (String plugin : plugins) {
if (plugin.equalsIgnoreCase(name)) {
correctname = plugin; // Fixes capitalization
break;
}
}
if (correctname == null) {
error(sender, "Can't find plugin: " + name);
return false;
}
info(sender, "Checking branch name...");
if (!TBMCCoreAPI.IsTestServer() && !branch.equalsIgnoreCase("master")) {
error(sender, "The server is in production mode, updating only allowed from master!");
return false;
}
Optional<String> correctbranch = GetPluginBranches(correctname).stream().filter(b -> b.equalsIgnoreCase(branch))
.findAny();
if (!correctbranch.isPresent()) {
error(sender, "Can't find branch \"" + branch + "\" for plugin \"" + correctname + "\"");
return false;
}
try {
if (DownloadString("https://raw.githubusercontent.com/TBMCPlugins/" + correctname + "/"
+ correctbranch.get() + "/pom.xml").equals("404: Not Found\n")) {
error(sender, "The plugin doesn't appear to have a pom.xml. Make sure it's a Maven project.");
return false;
}
} catch (IOException e1) {
error(sender, "The plugin doesn't appear to have a pom.xml. Make sure it's a Maven project.\n" + e1);
return false;
}
info(sender, "Updating TBMC plugin: " + correctname + " from " + correctbranch.get());
URL url;
final boolean isWindows = System.getProperty("os.name").contains("Windows");
File result = new File("plugins/" + correctname + (isWindows ? ".jar" : ".jar_tmp"));
File finalresult = new File("plugins/" + correctname + ".jar");
try {
url = new URL("https://jitpack.io/com/github/TBMCPlugins/"
+ (correctname.equals("ButtonCore") ? "ButtonCore/ButtonCore" : correctname) + "/"
+ correctbranch.get() + "-SNAPSHOT/" + correctname + "-" + correctbranch.get() + "-SNAPSHOT.jar"); // ButtonCore exception required since it hosts Towny as well
FileUtils.copyURLToFile(url, result);
if (!result.exists() || result.length() < 25) {
result.delete();
error(sender, "The downloaded JAR for " + correctname + " from " + correctbranch.get()
+ " is too small (smnaller than 25 bytes). Am I downloading from the right place?");
return false;
} else {
if (!isWindows)
Files.move(result.toPath(), finalresult.toPath(), StandardCopyOption.REPLACE_EXISTING);
info(sender, "Updating plugin " + correctname + " from " + correctbranch.get() + " done!");
return true;
}
} catch (FileNotFoundException e) {
error(sender,
"Can't find JAR for " + correctname + " from " + correctbranch.get()
+ ", the build probably failed. Build log (scroll to bottom):" + "\n"
+ "https://jitpack.io/com/github/TBMCPlugins/" + correctname + "/" + correctbranch.get()
+ "-SNAPSHOT/build.log\nIf you'd like to rebuild the same commit, go to:\nhttps://jitpack.io/#TBMCPlugins/"
+ correctname + "\nAnd delete the newest build.");
} catch (IOException e) {
error(sender, "IO error while updating " + correctname + "\n" + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
error(sender, "Unknown error while updating " + correctname + ": " + e);
}
return false;
}
private static void error(CommandSender sender, String message) {
if (!sender.equals(Bukkit.getConsoleSender()))
Bukkit.getLogger().warning(message);
sender.sendMessage("§c" + message);
}
private static void info(CommandSender sender, String message) {
if (!sender.equals(Bukkit.getConsoleSender()))
Bukkit.getLogger().info(message);
sender.sendMessage("§b" + message);
}
/**
* Retrieves all the repository names from the GitHub organization.
*
* @return A list of names
*/
public static List<String> GetPluginNames() {
List<String> ret = new ArrayList<>();
try {
String resp = DownloadString("https://api.github.com/orgs/TBMCPlugins/repos");
JsonArray arr = new JsonParser().parse(resp).getAsJsonArray();
for (JsonElement obj : arr) {
JsonObject jobj = obj.getAsJsonObject();
ret.add(jobj.get("name").getAsString());
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
/**
* Retrieves all the branches from the plugin repository.
*
* @return A list of names
*/
public static List<String> GetPluginBranches(String plugin) {
List<String> ret = new ArrayList<>();
try {
String resp = DownloadString("https://api.github.com/repos/TBMCPlugins/" + plugin + "/branches");
JsonArray arr = new JsonParser().parse(resp).getAsJsonArray();
for (JsonElement obj : arr) {
JsonObject jobj = obj.getAsJsonObject();
ret.add(jobj.get("name").getAsString());
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
return PluginUpdater.UpdatePlugin(name, sender, branch);
}
public static String DownloadString(String urlstr) throws MalformedURLException, IOException {

View file

@ -1,19 +1,39 @@
package buttondevteam.lib.chat;
public enum Color implements TellrawSerializableEnum {
Black("black"), DarkBlue("dark_blue"), DarkGreen("dark_green"), DarkAqua("dark_aqua"), DarkRed(
"dark_red"), DarkPurple("dark_purple"), Gold("gold"), Gray("gray"), DarkGray("dark_gray"), Blue(
"blue"), Green("green"), Aqua("aqua"), Red(
"red"), LightPurple("light_purple"), Yellow("yellow"), White("white"), RPC("rpc");
Black("black", 0, 0, 0), DarkBlue("dark_blue", 0, 0, 170), DarkGreen("dark_green", 0, 170, 0), DarkAqua("dark_aqua",
0, 170, 170), DarkRed("dark_red", 170, 0, 0), DarkPurple("dark_purple", 0, 170, 0), Gold("gold", 255, 170,
0), Gray("gray", 170, 170, 170), DarkGray("dark_gray", 85, 85, 85), Blue("blue", 85, 85,
255), Green("green", 85, 255, 85), Aqua("aqua", 85, 255, 255), Red("red", 255, 85,
85), LightPurple("light_purple", 255, 85, 255), Yellow("yellow", 255, 255,
85), White("white", 255, 255, 255), RPC("rpc", 0, 0, 0);
private String name;
private final String name;
private final int red;
private final int green;
private final int blue;
Color(String name) {
Color(String name, int red, int green, int blue) {
this.name = name;
this.red = red;
this.green = green;
this.blue = blue;
}
@Override
public String getName() {
return name;
}
public int getRed() {
return red;
}
public int getGreen() {
return green;
}
public int getBlue() {
return blue;
}
}

View file

@ -205,11 +205,11 @@ public abstract class ChromaGamerBase implements AutoCloseable {
* @return A data object with methods to get and set
*/
@SuppressWarnings("unchecked")
protected <T> PlayerData<T> data(String sectionname) {
protected <T> PlayerData<T> data(String sectionname, T def) {
ThrowIfNoUser();
String mname = sectionname + "." + new Exception().getStackTrace()[2].getMethodName();
if (!datamap.containsKey(mname))
datamap.put(mname, new PlayerData<T>(mname, plugindata));
datamap.put(mname, new PlayerData<T>(mname, plugindata, def));
return datamap.get(mname);
}
@ -219,11 +219,11 @@ public abstract class ChromaGamerBase implements AutoCloseable {
* @return A data object with methods to get and set
*/
@SuppressWarnings("unchecked")
protected <T> PlayerData<T> data() {
protected <T> PlayerData<T> data(T def) {
ThrowIfNoUser();
String mname = new Exception().getStackTrace()[1].getMethodName();
if (!datamap.containsKey(mname))
datamap.put(mname, new PlayerData<T>(mname, plugindata));
datamap.put(mname, new PlayerData<T>(mname, plugindata, def));
return datamap.get(mname);
}
@ -236,11 +236,11 @@ public abstract class ChromaGamerBase implements AutoCloseable {
* @return A data object with methods to get and set
*/
@SuppressWarnings("unchecked")
protected <T extends Enum<T>> EnumPlayerData<T> dataEnum(String sectionname, Class<T> cl) {
protected <T extends Enum<T>> EnumPlayerData<T> dataEnum(String sectionname, Class<T> cl, T def) {
ThrowIfNoUser();
String mname = sectionname + "." + new Exception().getStackTrace()[2].getMethodName();
if (!dataenummap.containsKey(mname))
dataenummap.put(mname, new EnumPlayerData<T>(mname, plugindata, cl));
dataenummap.put(mname, new EnumPlayerData<T>(mname, plugindata, cl, def));
return dataenummap.get(mname);
}
@ -250,11 +250,11 @@ public abstract class ChromaGamerBase implements AutoCloseable {
* @return A data object with methods to get and set
*/
@SuppressWarnings("unchecked")
protected <T extends Enum<T>> EnumPlayerData<T> dataEnum(Class<T> cl) {
protected <T extends Enum<T>> EnumPlayerData<T> dataEnum(Class<T> cl, T def) {
ThrowIfNoUser();
String mname = new Exception().getStackTrace()[1].getMethodName();
if (!dataenummap.containsKey(mname))
dataenummap.put(mname, new EnumPlayerData<T>(mname, plugindata, cl));
dataenummap.put(mname, new EnumPlayerData<T>(mname, plugindata, cl, def));
return dataenummap.get(mname);
}

View file

@ -5,25 +5,22 @@ import org.bukkit.configuration.file.YamlConfiguration;
public class EnumPlayerData<T extends Enum<T>> {
private PlayerData<String> data;
private Class<T> cl;
private T def;
public EnumPlayerData(String name, YamlConfiguration yaml, Class<T> cl) {
data = new PlayerData<String>(name, yaml);
public EnumPlayerData(String name, YamlConfiguration yaml, Class<T> cl, T def) {
data = new PlayerData<String>(name, yaml, "");
this.cl = cl;
this.def = def;
}
public T get() {
String str = data.get();
if (str == null || str.equals(""))
return null;
if (str.isEmpty())
return def;
return Enum.valueOf(cl, str);
}
public void set(T value) {
data.set(value.toString());
}
public T getOrDefault(T def) {
T value = get();
return value == null ? def : value;
}
}

View file

@ -5,15 +5,24 @@ import org.bukkit.configuration.file.YamlConfiguration;
public class PlayerData<T> {
private String name;
private YamlConfiguration yaml;
private T def;
public PlayerData(String name, YamlConfiguration yaml) {
public PlayerData(String name, YamlConfiguration yaml, T def) {
this.name = name;
this.yaml = yaml;
this.def = def;
}
@SuppressWarnings("unchecked")
// @Deprecated - What was once enforced (2 days ago from now) vanished now
public T get() {
Object value = yaml.get(name);
Object value = yaml.get(name, def);
if (value instanceof Integer) {
if (def instanceof Short) // If the default is Short the value must be as well because both are T
return (T) (Short) ((Integer) value).shortValue();
if (def instanceof Long)
return (T) (Long) ((Integer) value).longValue();
}
return (T) value;
}
@ -21,11 +30,6 @@ public class PlayerData<T> {
yaml.set(name, value);
}
public T getOrDefault(T def) {
T value = get();
return value == null ? def : value;
}
@Override
public String toString() {
return get().toString();

View file

@ -38,7 +38,7 @@ public abstract class TBMCPlayerBase extends ChromaGamerBase {
}
public PlayerData<String> PlayerName() {
return super.data();
return super.data(null);
}
/**
@ -47,8 +47,8 @@ public abstract class TBMCPlayerBase extends ChromaGamerBase {
* @return A data object with methods to get and set
*/
@Override
protected <T> PlayerData<T> data() {
return super.data(pluginname);
protected <T> PlayerData<T> data(T def) {
return super.data(pluginname, def);
}
/**
@ -57,8 +57,8 @@ public abstract class TBMCPlayerBase extends ChromaGamerBase {
* @return A data object with methods to get and set
*/
@Override
protected <T extends Enum<T>> EnumPlayerData<T> dataEnum(Class<T> cl) {
return super.dataEnum(pluginname, cl);
protected <T extends Enum<T>> EnumPlayerData<T> dataEnum(Class<T> cl, T def) {
return super.dataEnum(pluginname, cl, def);
}
/**

View file

@ -1,7 +1,12 @@
package buttondevteam.core;
import java.io.File;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import buttondevteam.core.TestPlayerClass.TestEnum;
import buttondevteam.lib.player.ChromaGamerBase;
import buttondevteam.lib.player.TBMCPlayerBase;
import junit.framework.Test;
import junit.framework.TestCase;
@ -19,28 +24,32 @@ public class PlayerDataTest extends TestCase {
return new TestSuite(PlayerDataTest.class);
}
public void testConfig() {
public void testConfig() throws Exception {
TestPrepare.PrepareServer();
FileUtils.deleteDirectory(new File(ChromaGamerBase.TBMC_PLAYERS_DIR));
UUID uuid = new UUID(0L, 0L);
try (TestPlayerClass p = TBMCPlayerBase.getPlayer(uuid, TestPlayerClass.class)) {
p.PlayerName().set("Test");
assertEquals("Test", p.PlayerName().get());
p.testenum().set(TestEnum.A);
assertEquals(TestEnum.A, p.testenum().get());
// p.TestShort().set((short) 5);
// assertEquals((short) 5, (short) (int) p.TestShort().get());
assertEquals((short) 0, (short) p.TestShort().get());
assertEquals(false, (boolean) p.TestBool().get());
p.testenum().set(TestEnum.B);
assertEquals(TestEnum.B, p.testenum().get());
p.TestShort().set((short) 5);
assertEquals((short) 5, (short) p.TestShort().get());
p.TestBool().set(true);
assertEquals(true, (boolean) p.TestBool().get());
} catch (Exception e) {
e.printStackTrace();
throw e;
}
try (TestPlayerClass p = TBMCPlayerBase.getPlayer(uuid, TestPlayerClass.class)) {
assertEquals("Test", p.PlayerName().get());
assertEquals(TestEnum.A, p.testenum().get());
// assertEquals((short) 5, (short) p.TestShort().get());
assertEquals(TestEnum.B, p.testenum().get());
assertEquals((short) 5, (short) p.TestShort().get());
assertEquals(true, (boolean) p.TestBool().get());
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}

View file

@ -8,7 +8,7 @@ import buttondevteam.lib.player.TBMCPlayerBase;
@PlayerClass(pluginname = "TestPlugin")
public class TestPlayerClass extends TBMCPlayerBase {
public EnumPlayerData<TestEnum> testenum() {
return dataEnum(TestEnum.class);
return dataEnum(TestEnum.class, TestEnum.A);
}
public enum TestEnum {
@ -16,10 +16,10 @@ public class TestPlayerClass extends TBMCPlayerBase {
}
public PlayerData<Short> TestShort() {
return data();
return data((short) 0);
}
public PlayerData<Boolean> TestBool() {
return data();
return data(false);
}
}