diff --git a/Core.iml b/Core.iml index 01c10d7..6e9fa8d 100644 --- a/Core.iml +++ b/Core.iml @@ -6,22 +6,21 @@ - - - - - - - - - - - - + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index 5695f41..f911ac1 100644 --- a/pom.xml +++ b/pom.xml @@ -61,14 +61,18 @@ org.spigotmc spigot-api - 1.10-R0.1-SNAPSHOT + 1.10.2-R0.1-SNAPSHOT provided + + org.bukkit + bukkit + 1.10.2-R0.1-SNAPSHOT + org.bukkit craftbukkit - 1.10-R0.1-SNAPSHOT - provided + 1.10.2-R0.1-SNAPSHOT org.mongodb diff --git a/src/main/java/eu/univento/cloud/client/CloudClient.java b/src/main/java/eu/univento/cloud/client/CloudClient.java index 084a26f..f5b203d 100644 --- a/src/main/java/eu/univento/cloud/client/CloudClient.java +++ b/src/main/java/eu/univento/cloud/client/CloudClient.java @@ -10,7 +10,7 @@ import io.netty.channel.socket.nio.NioSocketChannel; * @author joethei * @version 0.1 */ -public class CloudClient { +class CloudClient { public CloudClient() throws Exception{ NioEventLoopGroup child = new NioEventLoopGroup(); diff --git a/src/main/java/eu/univento/cloud/client/CloudManager.java b/src/main/java/eu/univento/cloud/client/CloudManager.java index 60266fa..e3b1cb6 100644 --- a/src/main/java/eu/univento/cloud/client/CloudManager.java +++ b/src/main/java/eu/univento/cloud/client/CloudManager.java @@ -5,6 +5,6 @@ package eu.univento.cloud.client; * @version 0.1 * created on 08.07.2016 */ -public class CloudManager { +class CloudManager { } \ No newline at end of file diff --git a/src/main/java/eu/univento/cloud/client/CloudMessenger.java b/src/main/java/eu/univento/cloud/client/CloudMessenger.java index 417e106..6052baf 100644 --- a/src/main/java/eu/univento/cloud/client/CloudMessenger.java +++ b/src/main/java/eu/univento/cloud/client/CloudMessenger.java @@ -19,6 +19,6 @@ public class CloudMessenger { HACK, CMD, AD, - ERROR; + ERROR } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/Core.java b/src/main/java/eu/univento/core/Core.java index cbe179b..f606f95 100644 --- a/src/main/java/eu/univento/core/Core.java +++ b/src/main/java/eu/univento/core/Core.java @@ -1,153 +1,105 @@ package eu.univento.core; import eu.univento.core.antihack.AntiHack; -import eu.univento.core.api.Blackscreen; import eu.univento.core.api.Config; import eu.univento.core.api.database.DatabaseManager; -import eu.univento.core.api.database.MongoDB; -import eu.univento.core.api.database.MySQL; +import eu.univento.core.api.effects.Blackscreen; import eu.univento.core.api.events.MoveEventFilter; import eu.univento.core.api.player.CustomPlayer; import eu.univento.core.api.server.NetworkData; import eu.univento.core.api.server.ServerSettings; +import eu.univento.core.api.utils.NettyInjection; import eu.univento.core.commands.*; import eu.univento.core.listeners.*; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import java.io.IOException; +import java.nio.channels.Channel; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * main class + * * @author joethei * @version 1.0 */ -public class Core extends JavaPlugin{ +public class Core extends JavaPlugin implements NettyInjection.PacketHandler { - //TODO: rewrite time critical database functions from MySQL to MongoDB - - /** - * plugin instance - */ - private static Core instance; - /** - * @return plugin instance - */ - public static Core getInstance() { - return instance; - } - - /** - * mysql stuff - */ - private static MySQL sql = new MySQL(getInstance(), Config.readString("MySQL.Host"), Config.readString("MySQL.Port"), Config.readString("MySQL.DB"), Config.readString("MySQL.User"), Config.readString("MySQL.Pass")); - /** - * @return sql - */ - public static MySQL getMySQL() { - return sql; - } + //TODO: rewrite database operations from sync MongoDB to async MongoDB - /* - private static AsyncMySQL asyncMySQL = new AsyncMySQL(getInstance(), Config.readString("MySQL.Host"), Config.readString("MySQL.Port"), Config.readString("MySQL.DB"), Config.readString("MySQL.User"), Config.readString("MySQL.Pass")); - public static AsyncMySQL getAsyncMySQL() { - return asyncMySQL; - } - */ - private static MongoDB mongoDB; - public static MongoDB getMongoDB() { - return mongoDB; + /** + * plugin instance + */ + private static Core instance; + + /** + * @return plugin instance + */ + public static Core getInstance() { + return instance; } - /* - private static AsyncMongoDB asyncMongoDB; - public static AsyncMongoDB getAsyncMongoDB() { - return asyncMongoDB; + private ArrayList registeredPlugins = new ArrayList<>(); + + public void registerPlugin(Plugin plugin) { + registeredPlugins.add(plugin.getName()); + } + + public void unregisterPlugin(Plugin plugin) { + if (registeredPlugins.contains(plugin.getName())) registeredPlugins.remove(plugin.getName()); + } + + private NettyInjection injection; + private static List timeout = new ArrayList<>(); + public static List getTimeout() { + return timeout; } - */ private static DatabaseManager databaseManager; + public static DatabaseManager getDatabaseManager() { return databaseManager; } - private static Logger log = Bukkit.getLogger(); + private static final Logger log = Bukkit.getLogger(); - public static ArrayList getOnlinePlayers() { - ArrayList list = new ArrayList<>(); - for(Player players : Bukkit.getOnlinePlayers()) { + public static Collection getOnlinePlayers() { + Collection list = new LinkedList<>(); + for (Player players : Bukkit.getOnlinePlayers()) { CustomPlayer p = CustomPlayer.getPlayer(players); list.add(p); } return list; } - /** - * @param level Log level - * @param string String - */ - public static void log(Level level, String string) { - if(ServerSettings.isDebug()) { + public static void broadcast(String key) { + for(CustomPlayer players : getOnlinePlayers()) { + players.sendMessage(players.getMessage(key)); + } + } + + /** + * @param level Log level + * @param string String + */ + public static void log(Level level, String string) { + if (ServerSettings.isDebug()) { log.log(level, "[univento Core] " + string); } - } + } - @Override - public void onEnable() { - ServerSettings.setDebug(true); - try { - Config.writeDefault(); - } catch (ClassNotFoundException | SQLException | IOException e) { - e.printStackTrace(); - } - instance = this; - log(Level.INFO, "activated debug mode"); - PluginManager pm = Bukkit.getPluginManager(); - pm.registerEvents(new Commands(), this); - pm.registerEvents(new JoinQuit(), this); - pm.registerEvents(new Chat(), this); - pm.registerEvents(new Events(), this); - pm.registerEvents(new MoveEventFilter(getServer()), this); - - if(ServerSettings.isGame()) { - new Fix(this, "fix", "fix"); - new Nick(this, "nick", "nick"); - } - AntiHack.registerListeners(); - - new RunAs(this, "RunAs", "runas"); - new SystemInfo(this, "SystemInfo", "systeminfo"); - new Vanish(this, "vanish", "vanish"); - new GameMode(this, "gamemode" , "gamemode", "gm"); - new SetRank(this, "setrank" , "setrank", "sr"); - new GlobalMute(this, "globalmute", "globalmute"); - new ChatClear(this, "chatclear", "chatclear", "cc"); - - log(Level.INFO, "registered all commands"); - - PluginMessenger pluginMessenger = new PluginMessenger(); - NetworkData networkData = new NetworkData(); - Bukkit.getMessenger().registerOutgoingPluginChannel(this, "5zig_Set"); - Bukkit.getMessenger().registerIncomingPluginChannel(this, "5zig_Set", pluginMessenger); - Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", networkData); - Bukkit.getMessenger().registerOutgoingPluginChannel(this, "LABYMOD"); - Bukkit.getMessenger().registerIncomingPluginChannel(this, "WDL|INIT", pluginMessenger); - Bukkit.getMessenger().registerOutgoingPluginChannel(this, "WDL|CONTROL"); - Bukkit.getMessenger().registerIncomingPluginChannel(this, "WDL|REQUEST", pluginMessenger); - Bukkit.getMessenger().registerIncomingPluginChannel(this, "PERMISSIONSREPL", pluginMessenger); - Bukkit.getMessenger().registerOutgoingPluginChannel(this, "schematica"); - - Blackscreen.setupUtil(getInstance()); - databaseManager = new DatabaseManager(getInstance()); - mongoDB = new MongoDB(Config.readString("MongoDB.Host"), Config.readInt("MongoDB.Port"), Config.readString("MongoDB.User"), Config.readString("MongoDB.Password"), Config.readString("MongoDB.Database")); - //asyncMongoDB = new AsyncMongoDB(Config.readString("MongoDB.Host"), Config.readInt("MongoDB.Port"), Config.readString("MongoDB.User"), Config.readString("MongoDB.Password"), Config.readString("MongoDB.Database")); + @Override + public void onEnable() { log(Level.INFO, "\n" + "\n" + " \n" + @@ -175,6 +127,55 @@ public class Core extends JavaPlugin{ " \n" + " \n" + "\n"); + try { + Config.writeDefault(); + } catch (IOException | ClassNotFoundException | SQLException e) { + e.printStackTrace(); + } + instance = this; + PluginManager pm = Bukkit.getPluginManager(); + pm.registerEvents(new Commands(), this); + pm.registerEvents(new JoinQuit(), this); + pm.registerEvents(new Chat(), this); + pm.registerEvents(new Events(), this); + pm.registerEvents(new WeaponEvents(), this); + pm.registerEvents(new SpectatorEvents(), this); + pm.registerEvents(new MoveEventFilter(getServer()), this); + + if (ServerSettings.isBuild()) { + new Build(this, "build", "enables/disables the build mode", "b"); + } + + if (ServerSettings.isGame()) { + new Fix(this, "fix", "fix your self or other players"); + new Nick(this, "nick", "nick/unnick your self"); + } + AntiHack.registerListeners(); + + new RunAs(this, "RunAs", "run command as other player"); + new SystemInfo(this, "SystemInfo", "gives info about the server system"); + new Vanish(this, "vanish", "vanish/unvanish your self"); + new GameMode(this, "gamemode", "sets your gamemode", "gm"); + new SetRank(this, "setrank", "sets the rank for other players", "sr"); + new GlobalMute(this, "globalmute", "mutes the server"); + new ChatClear(this, "chatclear", "clears the chat", "cc"); + new Timeout(this, "timeout", "timeout other players"); + + PluginMessenger pluginMessenger = new PluginMessenger(); + NetworkData networkData = new NetworkData(); + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "5zig_Set"); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "5zig_Set", pluginMessenger); + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", networkData); + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "LABYMOD"); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "WDL|INIT", pluginMessenger); + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "WDL|CONTROL"); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "WDL|REQUEST", pluginMessenger); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "PERMISSIONSREPL", pluginMessenger); + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "schematica"); + + Blackscreen.setupUtil(getInstance()); + databaseManager = new DatabaseManager(getInstance()); Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> log(Level.INFO, "\n" + "\n" + "\n" + @@ -187,19 +188,33 @@ public class Core extends JavaPlugin{ " \n" + " \n" + "\n"), 0L); - } - - @Override - public void onDisable() { - mongoDB.getClient().close(); - databaseManager.closeConnections(); - Bukkit.getMessenger().unregisterOutgoingPluginChannel(this, "BungeeCord"); - Bukkit.getMessenger().unregisterIncomingPluginChannel(this, "BungeeCord"); - Bukkit.getMessenger().unregisterOutgoingPluginChannel(this, "LABYMOD"); - Bukkit.getMessenger().unregisterIncomingPluginChannel(this, "WDL_INIT"); - Bukkit.getMessenger().unregisterOutgoingPluginChannel(this, "WDL|CONTROL"); + Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> { + for (Plugin plugin : pm.getPlugins()) { + if (!plugin.getName().equalsIgnoreCase("WorldEdit") && !plugin.getName().equalsIgnoreCase("VoxelSniper") && !registeredPlugins.contains(plugin.getName())) { + log(Level.WARNING, "§cDas Plugin " + plugin.getName() + " ist nicht für den Server zugelassen."); + } + } + }, 5L); - log(Level.INFO, "\n" + + this.injection = new NettyInjection(this, this.getName()); + this.injection.addHandler("TIMEOUT", new NettyInjection.PacketHandler() { + public Object onPacketIn(Player sender, Channel channel, Object packet) { + if (timeout.contains(CustomPlayer.getPlayer(sender))) + return null; + return packet; + } + }); + } + + @Override + public void onDisable() { + databaseManager.closeConnections(); + Bukkit.getMessenger().unregisterIncomingPluginChannel(this); + Bukkit.getMessenger().unregisterOutgoingPluginChannel(this); + + this.injection.disable(); + + log(Level.INFO, "\n" + "\n" + " \n" + " \n" + @@ -226,6 +241,6 @@ public class Core extends JavaPlugin{ " \n" + " \n" + "\nd"); - } + } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/antihack/AntiHack.java b/src/main/java/eu/univento/core/antihack/AntiHack.java index e4dcf69..228fd0d 100644 --- a/src/main/java/eu/univento/core/antihack/AntiHack.java +++ b/src/main/java/eu/univento/core/antihack/AntiHack.java @@ -5,6 +5,7 @@ import eu.univento.core.Core; import eu.univento.core.antihack.modules.*; import eu.univento.core.antihack.utils.PacketInjector; import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.WarnReason; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -15,7 +16,7 @@ import java.util.Map; public class AntiHack implements Listener{ - public static PacketInjector packetInjector = new PacketInjector(); + private static final PacketInjector packetInjector = new PacketInjector(); public static void registerListeners() { PluginManager pm = Bukkit.getPluginManager(); @@ -34,7 +35,8 @@ public class AntiHack implements Listener{ for(Map.Entry entry : AutoClicker.clicks.entrySet()) { if(entry.getValue() > 16) { CloudMessenger.sendHackMessage(Hack.AUTOCLICKER, entry.getKey()); - entry.getKey().warn(Hack.AUTOCLICKER); + //TODO: change to real warn reason + entry.getKey().warn(WarnReason.SPAM, null, "https://players.univento.eu/" + entry.getKey().getUniqueId().toString() + "/hacks"); } AutoClicker.clicks.remove(entry.getKey()); } diff --git a/src/main/java/eu/univento/core/antihack/Hack.java b/src/main/java/eu/univento/core/antihack/Hack.java index 1a50edf..f1dfc15 100644 --- a/src/main/java/eu/univento/core/antihack/Hack.java +++ b/src/main/java/eu/univento/core/antihack/Hack.java @@ -16,13 +16,13 @@ public enum Hack { NUKER(10); private int id; - private Hack(int id) { + Hack(int id) { this.setId(id); } public int getId() { return id; } - public void setId(int id) { + private void setId(int id) { this.id = id; } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/antihack/modules/AutoClicker.java b/src/main/java/eu/univento/core/antihack/modules/AutoClicker.java index ef2b1cc..fba81ee 100644 --- a/src/main/java/eu/univento/core/antihack/modules/AutoClicker.java +++ b/src/main/java/eu/univento/core/antihack/modules/AutoClicker.java @@ -10,7 +10,7 @@ import java.util.HashMap; public class AutoClicker implements Listener { - public static HashMap clicks = new HashMap<>(); + public static final HashMap clicks = new HashMap<>(); @EventHandler public void onClick(PlayerInteractEvent e) { diff --git a/src/main/java/eu/univento/core/antihack/modules/AutoRespawn.java b/src/main/java/eu/univento/core/antihack/modules/AutoRespawn.java index 7ab947d..5b738a1 100644 --- a/src/main/java/eu/univento/core/antihack/modules/AutoRespawn.java +++ b/src/main/java/eu/univento/core/antihack/modules/AutoRespawn.java @@ -3,6 +3,7 @@ package eu.univento.core.antihack.modules; import eu.univento.cloud.client.CloudMessenger; import eu.univento.core.antihack.Hack; import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.WarnReason; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; @@ -12,7 +13,7 @@ import java.util.HashMap; public class AutoRespawn implements Listener { - private HashMap time = new HashMap<>(); + private final HashMap time = new HashMap<>(); @EventHandler public void onDeath(PlayerDeathEvent e) { @@ -25,7 +26,8 @@ public class AutoRespawn implements Listener { if(time.containsKey(p)) { if(System.currentTimeMillis() - time.get(p) <= 200L) { CloudMessenger.sendHackMessage(Hack.AUTORESPAWN, p); - p.warn(Hack.AUTORESPAWN); + //TODO: change to real warn reason + p.warn(WarnReason.SPAM, null, "https://players.univento.eu/" + p.getUniqueId().toString() + "/hacks"); } time.remove(p); } diff --git a/src/main/java/eu/univento/core/antihack/modules/Criticals.java b/src/main/java/eu/univento/core/antihack/modules/Criticals.java index 9c9ad1e..de5c94f 100644 --- a/src/main/java/eu/univento/core/antihack/modules/Criticals.java +++ b/src/main/java/eu/univento/core/antihack/modules/Criticals.java @@ -4,6 +4,7 @@ import eu.univento.cloud.client.CloudMessenger; import eu.univento.core.Core; import eu.univento.core.antihack.Hack; import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.WarnReason; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -15,7 +16,7 @@ import java.util.ArrayList; public class Criticals implements Listener { - private ArrayList players = new ArrayList<>(); + private final ArrayList players = new ArrayList<>(); @EventHandler public void onEntityDamageByEntity(EntityDamageByEntityEvent e) { @@ -48,7 +49,8 @@ public class Criticals implements Listener { } if (fark == 0.125 || fark == 1.0 || fark == 1.3 || fark == 0.6190840103302007 || fark == 0.4414162352399398 || fark == 200.0) { CloudMessenger.sendHackMessage(Hack.CRITICALS, p); - p.warn(Hack.CRITICALS); + //TODO: change to real warn reason + p.warn(WarnReason.SPAM, null, "https://players.univento.eu/" + p.getUniqueId().toString() + "/hacks"); } }, 6L); } diff --git a/src/main/java/eu/univento/core/antihack/modules/FastPlace.java b/src/main/java/eu/univento/core/antihack/modules/FastPlace.java index 87eca15..66a6de4 100644 --- a/src/main/java/eu/univento/core/antihack/modules/FastPlace.java +++ b/src/main/java/eu/univento/core/antihack/modules/FastPlace.java @@ -3,6 +3,7 @@ package eu.univento.core.antihack.modules; import eu.univento.cloud.client.CloudMessenger; import eu.univento.core.antihack.Hack; import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.WarnReason; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPlaceEvent; @@ -11,7 +12,7 @@ import java.util.HashMap; public class FastPlace implements Listener{ - private HashMap time = new HashMap<>(); + private final HashMap time = new HashMap<>(); @EventHandler public void onPlace(BlockPlaceEvent e) { @@ -19,7 +20,8 @@ public class FastPlace implements Listener{ if(time.containsKey(p)) { if(System.currentTimeMillis() - time.get(p) <= 110L) { CloudMessenger.sendHackMessage(Hack.FASTPLACE, p); - p.warn(Hack.FASTPLACE); + //TODO: change to real warn reason + p.warn(WarnReason.ADVERTISEMENT, null, "https://players.univento.eu/" + p.getUniqueId().toString() + "/hacks"); } } time.put(p, System.currentTimeMillis()); diff --git a/src/main/java/eu/univento/core/antihack/modules/KillAura.java b/src/main/java/eu/univento/core/antihack/modules/KillAura.java index bc3fb0c..ffd1dc0 100644 --- a/src/main/java/eu/univento/core/antihack/modules/KillAura.java +++ b/src/main/java/eu/univento/core/antihack/modules/KillAura.java @@ -16,7 +16,7 @@ import java.util.UUID; public class KillAura implements Listener{ - public static HashMap players = new HashMap<>(); + public static final HashMap players = new HashMap<>(); @EventHandler public void onEntityDamage(EntityDamageByEntityEvent e) { diff --git a/src/main/java/eu/univento/core/antihack/modules/Nuker.java b/src/main/java/eu/univento/core/antihack/modules/Nuker.java index 9c57c07..92e1ee1 100644 --- a/src/main/java/eu/univento/core/antihack/modules/Nuker.java +++ b/src/main/java/eu/univento/core/antihack/modules/Nuker.java @@ -3,6 +3,7 @@ package eu.univento.core.antihack.modules; import eu.univento.cloud.client.CloudMessenger; import eu.univento.core.antihack.Hack; import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.WarnReason; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; @@ -14,10 +15,10 @@ import java.util.LinkedHashMap; * @version 0.1 * created on 01.07.2016 */ -public class Nuker implements Listener { +class Nuker implements Listener { - private LinkedHashMap last = new LinkedHashMap<>(); - private LinkedHashMap blocks = new LinkedHashMap<>(); + private final LinkedHashMap last = new LinkedHashMap<>(); + private final LinkedHashMap blocks = new LinkedHashMap<>(); @EventHandler public void onBlockBreak(BlockBreakEvent e) { @@ -28,7 +29,7 @@ public class Nuker implements Listener { if(blocks.get(p) > 80) { e.setCancelled(true); CloudMessenger.sendHackMessage(Hack.NUKER, p); - p.warn(Hack.NUKER); + p.warn(WarnReason.SPAM, null, "https://players.univento.eu/" + p.getUniqueId().toString() + "/hacks"); } }else{ blocks.put(p, 0); diff --git a/src/main/java/eu/univento/core/antihack/modules/Regen.java b/src/main/java/eu/univento/core/antihack/modules/Regen.java index f637b0f..54892ad 100644 --- a/src/main/java/eu/univento/core/antihack/modules/Regen.java +++ b/src/main/java/eu/univento/core/antihack/modules/Regen.java @@ -4,6 +4,7 @@ import eu.univento.cloud.client.CloudMessenger; import eu.univento.core.Core; import eu.univento.core.antihack.Hack; import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.WarnReason; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -14,8 +15,8 @@ import java.util.ArrayList; public class Regen implements Listener { - private ArrayList a = new ArrayList<>(); - private ArrayList b = new ArrayList<>(); + private final ArrayList a = new ArrayList<>(); + private final ArrayList b = new ArrayList<>(); @EventHandler public void onRegainHealth(EntityRegainHealthEvent e) { @@ -29,7 +30,8 @@ public class Regen implements Listener { if (e.getAmount() > 1.0) { p.setFoodLevel(0); CloudMessenger.sendHackMessage(Hack.REGEN, p); - p.warn(Hack.REGEN); + //TODO: change to real warn reason + p.warn(WarnReason.SPAM, null, "https://players.univento.eu/" + p.getUniqueId().toString() + "/hacks"); return; } if (!b.contains(p) && !a.contains(p)) { @@ -40,7 +42,8 @@ public class Regen implements Listener { p.setFoodLevel(0); b.remove(p); CloudMessenger.sendHackMessage(Hack.REGEN, p); - p.warn(Hack.REGEN); + //TODO: change to real warn reason + p.warn(WarnReason.SPAM, null, "https://players.univento.eu/" + p.getUniqueId().toString() + "/hacks"); } else if (a.contains(p)) { a.remove(p); b.remove(p); diff --git a/src/main/java/eu/univento/core/antihack/utils/PacketHandler.java b/src/main/java/eu/univento/core/antihack/utils/PacketHandler.java index f93b5a4..de65369 100644 --- a/src/main/java/eu/univento/core/antihack/utils/PacketHandler.java +++ b/src/main/java/eu/univento/core/antihack/utils/PacketHandler.java @@ -7,6 +7,7 @@ import eu.univento.core.antihack.Hack; import eu.univento.core.antihack.modules.KillAura; import eu.univento.core.api.fakeplayer.FakePlayer; import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.WarnReason; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; @@ -18,12 +19,12 @@ import java.util.HashMap; import java.util.Random; import java.util.UUID; -public class PacketHandler extends ChannelDuplexHandler { - private Player player; - private HashMap killAura = new HashMap<>(); - private HashMap count = new HashMap<>(); - private HashMap inventory = new HashMap<>(); - private ArrayList swing = new ArrayList<>(); +class PacketHandler extends ChannelDuplexHandler { + private final Player player; + private final HashMap killAura = new HashMap<>(); + private final HashMap count = new HashMap<>(); + private final HashMap inventory = new HashMap<>(); + private final ArrayList swing = new ArrayList<>(); public PacketHandler(final Player player) { this.player = player; @@ -33,7 +34,7 @@ public class PacketHandler extends ChannelDuplexHandler { super.write(ctx, msg, promise); } - public void destroy(final FakePlayer fp, Player p) { + private void destroy(final FakePlayer fp, Player p) { Bukkit.getScheduler().runTaskLater(Core.getInstance(), () -> { fp.removeTablist(); fp.despawn(); @@ -72,7 +73,7 @@ public class PacketHandler extends ChannelDuplexHandler { count.remove(player); CustomPlayer p = CustomPlayer.getPlayer(player); CloudMessenger.sendHackMessage(Hack.KILLAURA, p); - p.warn(Hack.KILLAURA); + p.warn(WarnReason.SPAM, null, "https://players.univento.eu/" + p.getUniqueId().toString() + "/hacks"); } killAura.remove(player); } diff --git a/src/main/java/eu/univento/core/antihack/utils/PacketInjector.java b/src/main/java/eu/univento/core/antihack/utils/PacketInjector.java index 2f5c1de..3b27881 100644 --- a/src/main/java/eu/univento/core/antihack/utils/PacketInjector.java +++ b/src/main/java/eu/univento/core/antihack/utils/PacketInjector.java @@ -8,29 +8,27 @@ import java.lang.reflect.Field; public class PacketInjector { private Field EntityPlayer_playerConnection; - private Class PlayerConnection; private Field PlayerConnection_networkManager; - private Class NetworkManager; private Field k; private Field m; public PacketInjector() { try { this.EntityPlayer_playerConnection = Reflection.getField(Reflection.getClass("{nms}.EntityPlayer"), "playerConnection"); - this.PlayerConnection = Reflection.getClass("{nms}.PlayerConnection"); - this.PlayerConnection_networkManager = Reflection.getField(this.PlayerConnection, "networkManager"); - this.NetworkManager = Reflection.getClass("{nms}.NetworkManager"); + Class playerConnection = Reflection.getClass("{nms}.PlayerConnection"); + this.PlayerConnection_networkManager = Reflection.getField(playerConnection, "networkManager"); + Class networkManager = Reflection.getClass("{nms}.NetworkManager"); Field[] fields2; - for (int length = (fields2 = this.NetworkManager.getFields()).length, i = 0; i < length; ++i) { + for (int length = (fields2 = networkManager.getFields()).length, i = 0; i < length; ++i) { final Field fields = fields2[i]; if (fields.getType().equals(Channel.class)) { this.k = fields; } } if (this.k == null) { - this.k = Reflection.getField(this.NetworkManager, "i"); + this.k = Reflection.getField(networkManager, "i"); } - this.m = Reflection.getField(this.NetworkManager, "m"); + this.m = Reflection.getField(networkManager, "m"); } catch (Throwable t) { t.printStackTrace(); } @@ -64,7 +62,7 @@ public class PacketInjector { } private Channel getChannel(final Object networkManager) { - Channel ch = null; + Channel ch; try { ch = Reflection.getFieldValue(this.k, networkManager); } catch (Exception e) { diff --git a/src/main/java/eu/univento/core/antihack/utils/PacketReader.java b/src/main/java/eu/univento/core/antihack/utils/PacketReader.java index 2ab1044..f3eab1b 100644 --- a/src/main/java/eu/univento/core/antihack/utils/PacketReader.java +++ b/src/main/java/eu/univento/core/antihack/utils/PacketReader.java @@ -10,10 +10,10 @@ import org.bukkit.entity.Player; import java.util.List; -public class PacketReader { +class PacketReader { - Player player; - Channel channel; + private final Player player; + private Channel channel; public PacketReader(final Player player) { this.player = player; @@ -22,7 +22,7 @@ public class PacketReader { public void inject() { final CraftPlayer player = (CraftPlayer) this.player; this.channel = player.getHandle().playerConnection.networkManager.channel; - this.channel.pipeline().addAfter("decoder", "PacketInjector", (ChannelHandler) new MessageToMessageDecoder>() { + this.channel.pipeline().addAfter("decoder", "PacketInjector", new MessageToMessageDecoder>() { protected void decode(final ChannelHandlerContext arg0, final Packet packet, final List arg2) throws Exception { arg2.add(packet); PacketReader.this.readPackets(packet); diff --git a/src/main/java/eu/univento/core/antihack/utils/Reflection.java b/src/main/java/eu/univento/core/antihack/utils/Reflection.java index 4aac220..d23fc18 100644 --- a/src/main/java/eu/univento/core/antihack/utils/Reflection.java +++ b/src/main/java/eu/univento/core/antihack/utils/Reflection.java @@ -8,7 +8,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; -public class Reflection { +class Reflection { public static Class getClass(final String classname) { try { final String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; @@ -21,13 +21,13 @@ public class Reflection { } public static Object getNmsPlayer(final Player p) throws Exception { - final Method getHandle = p.getClass().getMethod("getHandle", (Class[]) new Class[0]); - return getHandle.invoke(p, new Object[0]); + final Method getHandle = p.getClass().getMethod("getHandle"); + return getHandle.invoke(p); } public static Object getNmsScoreboard(final Scoreboard s) throws Exception { - final Method getHandle = s.getClass().getMethod("getHandle", (Class[]) new Class[0]); - return getHandle.invoke(s, new Object[0]); + final Method getHandle = s.getClass().getMethod("getHandle"); + return getHandle.invoke(s); } public static Object getFieldValue(final Object instance, final String fieldName) throws Exception { diff --git a/src/main/java/eu/univento/core/api/Actionbar.java b/src/main/java/eu/univento/core/api/Actionbar.java deleted file mode 100644 index 3bf28ea..0000000 --- a/src/main/java/eu/univento/core/api/Actionbar.java +++ /dev/null @@ -1,18 +0,0 @@ -package eu.univento.core.api; - -import net.minecraft.server.v1_10_R1.IChatBaseComponent; -import net.minecraft.server.v1_10_R1.IChatBaseComponent.ChatSerializer; -import net.minecraft.server.v1_10_R1.PacketPlayOutChat; -import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; -import org.bukkit.entity.Player; - -public class Actionbar { - - public static void send(Player player, String message){ - CraftPlayer p = (CraftPlayer) player; - IChatBaseComponent cbc = ChatSerializer.a("{\"text\": \"" + message + "\"}"); - PacketPlayOutChat ppoc = new PacketPlayOutChat(cbc,(byte) 2); - p.getHandle().playerConnection.sendPacket(ppoc); - } - -} diff --git a/src/main/java/eu/univento/core/api/AutoCommand.java b/src/main/java/eu/univento/core/api/AutoCommand.java index c36f742..3d6e20f 100644 --- a/src/main/java/eu/univento/core/api/AutoCommand.java +++ b/src/main/java/eu/univento/core/api/AutoCommand.java @@ -15,7 +15,7 @@ import java.util.logging.Level; /** * @author PostCrafter - * @see //http://postcrafter.de/viewtopic.php?f=15&t=143 + * @see "http://postcrafter.de/viewtopic.php?f=15&t=143" * @param

main class */ public abstract class AutoCommand

extends Command { @@ -28,8 +28,8 @@ public abstract class AutoCommand

extends Command { Core.log(Level.INFO, "AutoCommand hook for Bukkit " + AutoCommand.VERSION); } - protected final P plugin; - protected final String command; + private final P plugin; + private final String command; public AutoCommand(P plugin, String command, String description, String... aliases) { super(command); diff --git a/src/main/java/eu/univento/core/api/Blackscreen.java b/src/main/java/eu/univento/core/api/Blackscreen.java deleted file mode 100644 index 7091575..0000000 --- a/src/main/java/eu/univento/core/api/Blackscreen.java +++ /dev/null @@ -1,80 +0,0 @@ -package eu.univento.core.api; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -/** - * - * @author janhektor - * - */ -public class Blackscreen { - private static Object packetObject; - private static Class packetClass; - private static String VERSION; - private static Map ticksLeft = new HashMap(); - - static { String path = Bukkit.getServer().getClass().getPackage().getName(); - VERSION = path.substring(path.lastIndexOf(".") + 1, path.length()); - try { - packetClass = Class.forName("net.minecraft.server." + VERSION + ".Packet"); - Class packetGameStateClass = Class.forName("net.minecraft.server." + VERSION + ".PacketPlayOutGameStateChange"); - packetObject = packetGameStateClass.getConstructor(new Class[] { Integer.TYPE, Float.TYPE }).newInstance(new Object[] { Integer.valueOf(4), Integer.valueOf(0) }); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static void setupUtil(Plugin instance) - { - setupUtil(instance, 2); - } - - public static void setupUtil(Plugin instance, int repeatingTicks) - { - Bukkit.getScheduler().runTaskTimer(instance, () -> { - for (UUID uuid : Blackscreen.ticksLeft.keySet()) { - Player p = Bukkit.getPlayer(uuid); - if (p == null) { - Blackscreen.ticksLeft.remove(uuid); - } - else if (((Integer)Blackscreen.ticksLeft.get(uuid)).intValue() > 0) { - Blackscreen.ticksLeft.put(uuid, Integer.valueOf((Blackscreen.ticksLeft.get(uuid)).intValue() - 2)); - Blackscreen.access(p); - } else { - Blackscreen.ticksLeft.remove(uuid); - } - } - } - , 0L, repeatingTicks); - } - - protected static void access(Player p) { - -} - -private static void sendPacket(Player p) { - try { - Object nmsPlayer = p.getClass().getMethod("getHandle", new Class[0]).invoke(p, new Object[0]); - Field playerConnectionField = nmsPlayer.getClass().getField("playerConnection"); - Object pConnection = playerConnectionField.get(nmsPlayer); - Method sendPacket = pConnection.getClass().getMethod("sendPacket", new Class[] { packetClass }); - sendPacket.invoke(pConnection, new Object[] { packetObject }); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static void setBlack(Player p, int seconds) - { - ticksLeft.put(p.getUniqueId(), Integer.valueOf(seconds * 20)); - sendPacket(p); - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/Config.java b/src/main/java/eu/univento/core/api/Config.java index 7ded2c1..aa77290 100644 --- a/src/main/java/eu/univento/core/api/Config.java +++ b/src/main/java/eu/univento/core/api/Config.java @@ -17,9 +17,9 @@ import java.sql.SQLException; public class Config { /**config file*/ - private static File file = new File("plugins/Core", "config.yml"); + private static final File file = new File("plugins/Core", "config.yml"); /**load configuration */ - private static FileConfiguration cfg = YamlConfiguration.loadConfiguration(file); + private static final FileConfiguration cfg = YamlConfiguration.loadConfiguration(file); /** * write default data to config @@ -49,11 +49,10 @@ public class Config { /** * write data as string to config - * @param path path to data * @param obj data */ - public static void write(String path, String obj) { - cfg.set(path, obj); + public static void write(String obj) { + cfg.set("lastPlot", obj); try { cfg.save(file); } catch (IOException e) { @@ -119,11 +118,10 @@ public class Config { /** * read integer from config - * @param path path to data * @return Integer */ - public static int readInt(String path) { - return cfg.getInt(path); + public static int readInt() { + return cfg.getInt("MongoDB.Port"); } /** diff --git a/src/main/java/eu/univento/core/api/Hologram.java b/src/main/java/eu/univento/core/api/Hologram.java index 306471e..82dc258 100644 --- a/src/main/java/eu/univento/core/api/Hologram.java +++ b/src/main/java/eu/univento/core/api/Hologram.java @@ -12,10 +12,9 @@ import java.util.List; public class Hologram { - private List entitylist = new ArrayList<>(); - private String[] text; - private Location location; - private double DISTANCE = 0.25D; + private final List entitylist = new ArrayList<>(); + private final String[] text; + private final Location location; private int count; public Hologram(String[] text, Location location) { @@ -51,7 +50,7 @@ public class Hologram { } } - public void showAll() { + private void showAll() { for (CustomPlayer player : Core.getOnlinePlayers()) { for (EntityArmorStand armor : entitylist) { PacketPlayOutSpawnEntityLiving packet = new PacketPlayOutSpawnEntityLiving(armor); @@ -60,7 +59,7 @@ public class Hologram { } } - public void hideAll() { + private void hideAll() { for (CustomPlayer player : Core.getOnlinePlayers()) { for (EntityArmorStand armor : entitylist) { PacketPlayOutEntityDestroy packet = new PacketPlayOutEntityDestroy(armor.getId()); @@ -70,6 +69,7 @@ public class Hologram { } private void create() { + double DISTANCE = 0.25D; for (String text : this.text) { EntityArmorStand entity = new EntityArmorStand(((CraftWorld) this.location.getWorld()).getHandle(),this.location.getX(), this.location.getY(),this.location.getZ()); entity.setCustomName(text); @@ -77,12 +77,12 @@ public class Hologram { entity.setInvisible(true); entity.setNoGravity(true); entitylist.add(entity); - this.location.subtract(0, this.DISTANCE, 0); + this.location.subtract(0, DISTANCE, 0); count++; } for (int i = 0; i < count; i++) { - this.location.add(0, this.DISTANCE, 0); + this.location.add(0, DISTANCE, 0); } this.count = 0; } diff --git a/src/main/java/eu/univento/core/api/Title.java b/src/main/java/eu/univento/core/api/Title.java deleted file mode 100644 index a56f295..0000000 --- a/src/main/java/eu/univento/core/api/Title.java +++ /dev/null @@ -1,85 +0,0 @@ -package eu.univento.core.api; - -import net.minecraft.server.v1_10_R1.IChatBaseComponent; -import net.minecraft.server.v1_10_R1.PacketPlayOutPlayerListHeaderFooter; -import net.minecraft.server.v1_10_R1.PacketPlayOutTitle; -import net.minecraft.server.v1_10_R1.PlayerConnection; -import org.bukkit.ChatColor; -import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; -import org.bukkit.entity.Player; - -import java.lang.reflect.Field; - -//TODO: find real author, its not me -/** - * sends title to player - * @author joethei - * @version 1.0 - */ -public class Title { - - /** - * send title to player - * @param player Player - * @param fadeIn Integer - * @param stay Integer - * @param fadeOut Integer - * @param title String - * @param subtitle String - */ - public static void sendTitle(Player player, Integer fadeIn, Integer stay, Integer fadeOut, String title, String subtitle) { - PlayerConnection connection = ((CraftPlayer) player).getHandle().playerConnection; - - PacketPlayOutTitle packetPlayOutTimes = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TIMES, null, fadeIn, stay, fadeOut); - connection.sendPacket(packetPlayOutTimes); - - if (subtitle != null) { - subtitle = subtitle.replaceAll("%player%", player.getDisplayName()); - subtitle = ChatColor.translateAlternateColorCodes('&', subtitle); - IChatBaseComponent titleSub = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + subtitle + "\"}"); - PacketPlayOutTitle packetPlayOutSubTitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.SUBTITLE, titleSub); - connection.sendPacket(packetPlayOutSubTitle); - } - - if (title != null) { - title = title.replaceAll("%player%", player.getDisplayName()); - title = ChatColor.translateAlternateColorCodes('&', title); - IChatBaseComponent titleMain = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + title + "\"}"); - PacketPlayOutTitle packetPlayOutTitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TITLE, titleMain); - connection.sendPacket(packetPlayOutTitle); - } - } - - /** - * sends tab title to player - * @param player Player - * @param header String - * @param footer String - */ - public static void sendTabTitle(Player player, String header, String footer) { - if (header == null) - header = ""; - header = ChatColor.translateAlternateColorCodes('&', header); - - if (footer == null) - footer = ""; - footer = ChatColor.translateAlternateColorCodes('&', footer); - - header = header.replaceAll("%player%", player.getDisplayName()); - footer = footer.replaceAll("%player%", player.getDisplayName()); - - PlayerConnection connection = ((CraftPlayer) player).getHandle().playerConnection; - IChatBaseComponent tabTitle = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + header + "\"}"); - IChatBaseComponent tabFoot = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + footer + "\"}"); - PacketPlayOutPlayerListHeaderFooter headerPacket = new PacketPlayOutPlayerListHeaderFooter(tabTitle); - try { - Field field = headerPacket.getClass().getDeclaredField("b"); - field.setAccessible(true); - field.set(headerPacket, tabFoot); - } catch (Exception e) { - e.printStackTrace(); - } finally { - connection.sendPacket(headerPacket); - } - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/Utils.java b/src/main/java/eu/univento/core/api/Utils.java index f3e1146..7b53db6 100644 --- a/src/main/java/eu/univento/core/api/Utils.java +++ b/src/main/java/eu/univento/core/api/Utils.java @@ -50,7 +50,7 @@ public class Utils { * deletes all folders and files in directory * @param file File */ - public static void deleteDir(File file) { + private static void deleteDir(File file) { if (file.isDirectory()) { if (file.list().length == 0) { file.delete(); @@ -155,7 +155,7 @@ public class Utils { * restarts server */ public static void restart() { - Bukkit.getScheduler().scheduleSyncDelayedTask(Core.getInstance(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "/restart"), 10 * 20L); + Bukkit.getScheduler().scheduleSyncDelayedTask(Core.getInstance(), () -> Bukkit.spigot().restart(), 10 * 20L); } /** diff --git a/src/main/java/eu/univento/core/api/customitems/CustomArmor.java b/src/main/java/eu/univento/core/api/customitems/CustomArmor.java new file mode 100644 index 0000000..5aba137 --- /dev/null +++ b/src/main/java/eu/univento/core/api/customitems/CustomArmor.java @@ -0,0 +1,11 @@ +package eu.univento.core.api.customitems; + +/** + * @author joethei + * @version 0.1 + * Created at 20:40 on 12.07.2016. + */ +public class CustomArmor { + + +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/customitems/CustomItemManager.java b/src/main/java/eu/univento/core/api/customitems/CustomItemManager.java new file mode 100644 index 0000000..7971c2c --- /dev/null +++ b/src/main/java/eu/univento/core/api/customitems/CustomItemManager.java @@ -0,0 +1,12 @@ +package eu.univento.core.api.customitems; + +/** + * @author joethei + * @version 0.1 + * Created at 20:39 on 12.07.2016. + */ +public class CustomItemManager { + + + +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/customitems/swords/BestSwordEver.java b/src/main/java/eu/univento/core/api/customitems/swords/BestSwordEver.java new file mode 100644 index 0000000..e4bf25b --- /dev/null +++ b/src/main/java/eu/univento/core/api/customitems/swords/BestSwordEver.java @@ -0,0 +1,46 @@ +package eu.univento.core.api.customitems.swords; + +import eu.univento.core.api.items.ItemBuilder; +import eu.univento.core.api.player.CustomPlayer; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +/** + * @author joethei + * @version 0.1 + * Created at 20:44 on 12.07.2016. + */ +public class BestSwordEver extends CustomSword { + + public BestSwordEver(CustomPlayer player) { + super(player); + } + + @Override + public void primaryAttack() { + player.getNearbyEntities(5.0D, 5.0D, 5.0D).stream().filter(entity -> entity instanceof Player).forEach(entity -> { + CustomPlayer p = CustomPlayer.getPlayer((Player) entity); + p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 5, 10)); + }); + player.sendMessage("Primäre Attacke genutzt"); + } + + @Override + public void secondaryAttack() { + player.sendMessage("Sekundäre Attacke genutzt"); + } + + @Override + public void sneakingAttack() { + player.sendMessage("Sneakende Attacke genutzt"); + } + + @Override + public ItemStack getItem() { + return new ItemBuilder(Material.DIAMOND_SWORD).name("§cBestSwordEver").durability((short) 20).enchantment(Enchantment.KNOCKBACK).make(); + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/customitems/swords/CustomSword.java b/src/main/java/eu/univento/core/api/customitems/swords/CustomSword.java new file mode 100644 index 0000000..9cbd5a5 --- /dev/null +++ b/src/main/java/eu/univento/core/api/customitems/swords/CustomSword.java @@ -0,0 +1,40 @@ +package eu.univento.core.api.customitems.swords; + +import eu.univento.core.api.customitems.swords.CustomSwordManager; +import eu.univento.core.api.player.CustomPlayer; +import org.bukkit.inventory.ItemStack; + +/** + * @author joethei + * @version 0.1 + * Created at 20:41 on 12.07.2016. + */ +public class CustomSword{ + + public CustomPlayer player; + + public CustomSword(CustomPlayer player) { + this.player = player; + CustomSwordManager.add(this); + } + + public void primaryAttack() { + + } + + public void secondaryAttack() { + + } + + public void sneakingAttack() { + + } + + public ItemStack getItem() { + return null; + } + + public void addItem() { + player.getInventory().addItem(getItem()); + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/customitems/swords/CustomSwordManager.java b/src/main/java/eu/univento/core/api/customitems/swords/CustomSwordManager.java new file mode 100644 index 0000000..2ed643a --- /dev/null +++ b/src/main/java/eu/univento/core/api/customitems/swords/CustomSwordManager.java @@ -0,0 +1,34 @@ +package eu.univento.core.api.customitems.swords; + +import org.bukkit.inventory.ItemStack; + +import java.util.LinkedList; +import java.util.List; + +/** + * @author joethei + * @version 1.0 + * Created at 20:56 on 12.07.2016. + */ +public class CustomSwordManager { + + private static List swords = new LinkedList<>(); + + public static CustomSword valueOf(ItemStack item) { + for(CustomSword sword : swords) + if(sword.getItem().equals(item)) return sword; + return null; + } + + public static void add(CustomSword sword) { + swords.add(sword); + } + + public static void remove(CustomSword sword) { + swords.remove(sword); + } + + public static boolean contains(CustomSword sword) { + return swords.contains(sword); + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/database/AsyncMongoDB.java b/src/main/java/eu/univento/core/api/database/AsyncMongoDB.java index dfca444..9679e8b 100644 --- a/src/main/java/eu/univento/core/api/database/AsyncMongoDB.java +++ b/src/main/java/eu/univento/core/api/database/AsyncMongoDB.java @@ -15,7 +15,7 @@ import java.util.List; public class AsyncMongoDB { - private MongoClient client; + private final MongoClient client; private MongoDatabase database; public AsyncMongoDB(String host, int port, String username, String password, String database) { @@ -28,9 +28,9 @@ public class AsyncMongoDB { client = MongoClients.create(settings); } - public MongoClient getClient() { + private MongoClient getClient() { if(client == null) - new AsyncMongoDB(Config.readString("MongoDB.Host"), Config.readInt("MongoDB.Port"), Config.readString("MongoDB.User"), Config.readString("MongoDB.Password"), Config.readString("MongoDB.Database")); + new AsyncMongoDB(Config.readString("MongoDB.Host"), Config.readInt(), Config.readString("MongoDB.User"), Config.readString("MongoDB.Password"), Config.readString("MongoDB.Database")); return client; } diff --git a/src/main/java/eu/univento/core/api/database/AsyncMySQL.java b/src/main/java/eu/univento/core/api/database/AsyncMySQL.java index 754a5c4..1234498 100644 --- a/src/main/java/eu/univento/core/api/database/AsyncMySQL.java +++ b/src/main/java/eu/univento/core/api/database/AsyncMySQL.java @@ -28,25 +28,15 @@ public class AsyncMySQL { } public void update(String update) { - executor.execute(() -> { - try { - sql.query(update); - } catch (SQLException | ClassNotFoundException e) { - e.printStackTrace(); - } - }); + executor.execute(() -> sql.query(update)); } public void query(String query, Consumer consumer) { executor.execute(() -> { ResultSet result = null; - try { - result = sql.query(query); - ResultSet finalResult = result; - Bukkit.getScheduler().runTask(plugin, () -> consumer.accept(finalResult)); - } catch (SQLException | ClassNotFoundException e) { - e.printStackTrace(); - } + result = sql.query(query); + ResultSet finalResult = result; + Bukkit.getScheduler().runTask(plugin, () -> consumer.accept(finalResult)); }); } diff --git a/src/main/java/eu/univento/core/api/database/Database.java b/src/main/java/eu/univento/core/api/database/Database.java index 185fe33..40856c8 100644 --- a/src/main/java/eu/univento/core/api/database/Database.java +++ b/src/main/java/eu/univento/core/api/database/Database.java @@ -4,19 +4,19 @@ import org.bukkit.plugin.Plugin; import java.sql.*; -public abstract class Database { - protected Connection connection; - protected Plugin plugin; +abstract class Database { + Connection connection; + final Plugin plugin; - protected Database(Plugin plugin) { + Database(Plugin plugin) { this.plugin = plugin; this.connection = null; } - public abstract Connection openConnection() + protected abstract Connection openConnection() throws SQLException, ClassNotFoundException; - public boolean checkConnection() + boolean checkConnection() throws SQLException { return (this.connection != null) && (!this.connection.isClosed()); } @@ -25,13 +25,12 @@ public abstract class Database { return this.connection; } - public boolean closeConnection() + public void closeConnection() throws SQLException { if (this.connection == null) { - return false; + return; } this.connection.close(); - return true; } public ResultSet query(String query) diff --git a/src/main/java/eu/univento/core/api/database/DatabaseManager.java b/src/main/java/eu/univento/core/api/database/DatabaseManager.java index cacf48f..8f42bec 100644 --- a/src/main/java/eu/univento/core/api/database/DatabaseManager.java +++ b/src/main/java/eu/univento/core/api/database/DatabaseManager.java @@ -3,8 +3,6 @@ package eu.univento.core.api.database; import eu.univento.core.api.Config; import org.bukkit.plugin.Plugin; -import java.sql.SQLException; - /** * @author joethei * @version 0.1 @@ -18,8 +16,8 @@ public class DatabaseManager { private static MySQL mysql; public DatabaseManager(Plugin plugin) { - asyncMongoDB = new AsyncMongoDB(Config.readString("MongoDB.Host"), Config.readInt("MongoDB.Port"), Config.readString("MongoDB.User"), Config.readString("MongoDB.Password"), Config.readString("MongoDB.Database")); - mongoDB = new MongoDB(Config.readString("MongoDB.Host"), Config.readInt("MongoDB.Port"), Config.readString("MongoDB.User"), Config.readString("MongoDB.Password"), Config.readString("MongoDB.Database")); + asyncMongoDB = new AsyncMongoDB(Config.readString("MongoDB.Host"), Config.readInt(), Config.readString("MongoDB.User"), Config.readString("MongoDB.Password"), Config.readString("MongoDB.Database")); + mongoDB = new MongoDB(Config.readString("MongoDB.Host"), Config.readInt(), Config.readString("MongoDB.User"), Config.readString("MongoDB.Password"), Config.readString("MongoDB.Database")); mysql = new MySQL(plugin, Config.readString("MySQL.Host"), Config.readString("MySQL.Port"), Config.readString("MySQL.DB"), Config.readString("MySQL.User"), Config.readString("MySQL.Pass")); asyncMySQL = new AsyncMySQL(plugin, Config.readString("MySQL.Host"), Config.readString("MySQL.Port"), Config.readString("MySQL.DB"), Config.readString("MySQL.User"), Config.readString("MySQL.Pass")); } @@ -27,12 +25,8 @@ public class DatabaseManager { public void closeConnections() { asyncMongoDB.closeConnection(); mongoDB.closeConnection(); - try { - mysql.closeConnection(); - asyncMySQL.getMySQL().closeConnection(); - } catch (SQLException e) { - e.printStackTrace(); - } + mysql.close(); + asyncMySQL.getMySQL().close(); } public AsyncMongoDB getAsyncMongoDB() { diff --git a/src/main/java/eu/univento/core/api/database/MongoDB.java b/src/main/java/eu/univento/core/api/database/MongoDB.java index 6191278..72c0a78 100644 --- a/src/main/java/eu/univento/core/api/database/MongoDB.java +++ b/src/main/java/eu/univento/core/api/database/MongoDB.java @@ -10,7 +10,7 @@ import java.util.Collections; public class MongoDB { - private MongoClient client; + private final MongoClient client; private MongoDatabase database; public MongoDB(String host, int port, String username, String password, String database) { @@ -18,9 +18,9 @@ public class MongoDB { client = new MongoClient(new ServerAddress(host, port), Collections.singletonList(credential)); } - public MongoClient getClient() { + private MongoClient getClient() { if(client == null) - new MongoDB(Config.readString("MongoDB.Host"), Config.readInt("MongoDB.Port"), Config.readString("MongoDB.User"), Config.readString("MongoDB.Password"), Config.readString("MongoDB.Database")); + new MongoDB(Config.readString("MongoDB.Host"), Config.readInt(), Config.readString("MongoDB.User"), Config.readString("MongoDB.Password"), Config.readString("MongoDB.Database")); return client; } diff --git a/src/main/java/eu/univento/core/api/database/MySQL.java b/src/main/java/eu/univento/core/api/database/MySQL.java index 8243d1f..f825227 100644 --- a/src/main/java/eu/univento/core/api/database/MySQL.java +++ b/src/main/java/eu/univento/core/api/database/MySQL.java @@ -1,12 +1,83 @@ package eu.univento.core.api.database; +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; import org.bukkit.plugin.Plugin; import java.sql.Connection; -import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; import java.sql.SQLException; -public class MySQL extends Database { +public class MySQL { + + private final Plugin plugin; + private final String username; + private final String database; + private final String password; + private final String port; + private final String hostname; + + private final HikariDataSource dataSource; + + public MySQL(Plugin plugin, String hostname, String port, String database, String username, String password) { + this.plugin = plugin; + this.username = username; + this.database = database; + this.password = password; + this.port = port; + this.hostname = hostname; + HikariConfig config = new HikariConfig(); + config.setJdbcUrl("jdbc:mysql://" + hostname + ":" + port + "/" + database); + config.setUsername(username); + config.setPassword(password); + config.addDataSourceProperty("cachePrepStmts", "true"); + config.addDataSourceProperty("prepStmtCacheSize", "250"); + config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); + + dataSource = new HikariDataSource(config); + } + + void close() { + dataSource.close(); + } + + public HikariDataSource getDataSource() { + return dataSource; + } + + public Connection getConnection() { + try { + if (dataSource.getConnection() != null) + return dataSource.getConnection(); + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } + + public int update(String sql) { + try { + PreparedStatement statement = getConnection().prepareStatement(sql); + return statement.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } + return 0; + } + + public ResultSet query(String sql) { + PreparedStatement statement; + try { + statement = getConnection().prepareStatement(sql); + return statement.executeQuery(); + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } + + /* private final String user; private final String database; private final String password; @@ -29,4 +100,5 @@ public class MySQL extends Database { this.connection = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database, this.user, this.password); return this.connection; } + */ } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/database/SQLite.java b/src/main/java/eu/univento/core/api/database/SQLite.java deleted file mode 100644 index 51961a1..0000000 --- a/src/main/java/eu/univento/core/api/database/SQLite.java +++ /dev/null @@ -1,47 +0,0 @@ -package eu.univento.core.api.database; - -import org.bukkit.plugin.Plugin; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.logging.Level; - -public class SQLite extends Database -{ - private final String dbLocation; - - public SQLite(Plugin plugin, String dbLocation) - { - super(plugin); - this.dbLocation = dbLocation; - } - - public Connection openConnection() - throws SQLException, ClassNotFoundException - { - if (checkConnection()) { - return this.connection; - } - if (!this.plugin.getDataFolder().exists()) { - this.plugin.getDataFolder().mkdirs(); - } - File file = new File(this.plugin.getDataFolder(), this.dbLocation); - if (!file.exists()) { - try { - file.createNewFile(); - } catch (IOException e) { - this.plugin.getLogger().log(Level.SEVERE, - "Unable to create database!"); - } - } - Class.forName("org.sqlite.JDBC"); - this.connection = - DriverManager.getConnection("jdbc:sqlite:" + - this.plugin.getDataFolder().toPath().toString() + "/" + - this.dbLocation); - return this.connection; - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/effects/Blackscreen.java b/src/main/java/eu/univento/core/api/effects/Blackscreen.java new file mode 100644 index 0000000..ad4bf9c --- /dev/null +++ b/src/main/java/eu/univento/core/api/effects/Blackscreen.java @@ -0,0 +1,65 @@ +package eu.univento.core.api.effects; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * @author janhektor + */ +public class Blackscreen { + private static Object packetObject; + private static Class packetClass; + private static Map ticksLeft = new HashMap<>(); + + static { + String path = Bukkit.getServer().getClass().getPackage().getName(); + String VERSION = path.substring(path.lastIndexOf(".") + 1, path.length()); + try { + packetClass = Class.forName("net.minecraft.server." + VERSION + ".Packet"); + Class packetGameStateClass = Class.forName("net.minecraft.server." + VERSION + ".PacketPlayOutGameStateChange"); + packetObject = packetGameStateClass.getConstructor(new Class[]{Integer.TYPE, Float.TYPE}).newInstance(4, 0); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static void setupUtil(Plugin instance) { + Bukkit.getScheduler().runTaskTimer(instance, () -> { + for (UUID uuid : Blackscreen.ticksLeft.keySet()) { + Player p = Bukkit.getPlayer(uuid); + if (p == null) { + Blackscreen.ticksLeft.remove(uuid); + } else if (Blackscreen.ticksLeft.get(uuid) > 0) { + Blackscreen.ticksLeft.put(uuid, Blackscreen.ticksLeft.get(uuid) - 2); + } else { + Blackscreen.ticksLeft.remove(uuid); + } + } + } + , 0L, 2); + } + + private static void sendPacket(Player p) { + try { + Object nmsPlayer = p.getClass().getMethod("getHandle", new Class[0]).invoke(p); + Field playerConnectionField = nmsPlayer.getClass().getField("playerConnection"); + Object pConnection = playerConnectionField.get(nmsPlayer); + Method sendPacket = pConnection.getClass().getMethod("sendPacket", packetClass); + sendPacket.invoke(pConnection, packetObject); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static void setBlack(Player p, int seconds) { + ticksLeft.put(p.getUniqueId(), seconds * 20); + sendPacket(p); + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/effects/Effects.java b/src/main/java/eu/univento/core/api/effects/Effects.java index 5f072bc..f36a14f 100644 --- a/src/main/java/eu/univento/core/api/effects/Effects.java +++ b/src/main/java/eu/univento/core/api/effects/Effects.java @@ -1,6 +1,7 @@ package eu.univento.core.api.effects; import eu.univento.core.Core; +import eu.univento.core.api.player.CustomPlayer; import net.minecraft.server.v1_10_R1.EnumParticle; import net.minecraft.server.v1_10_R1.PacketPlayOutWorldParticles; import org.bukkit.Location; @@ -18,12 +19,11 @@ public class Effects { * plays effects from location * @param loc Location * @param ep EnumParticle - * @param f float of particles * @param count count of particles */ - public static void playEffect(Location loc, EnumParticle ep, float f, int count) { - PacketPlayOutWorldParticles packet = new PacketPlayOutWorldParticles(ep, true, (float) loc.getX(), (float) loc.getY(), (float) loc.getZ(), f, f, f, 0.0F, count, 0, 0); - Core.getOnlinePlayers().stream().filter(p -> p.hasEffects()).forEach(p -> p.getHandle().playerConnection.sendPacket(packet)); + public static void playEffect(Location loc, EnumParticle ep, int count) { + PacketPlayOutWorldParticles packet = new PacketPlayOutWorldParticles(ep, true, (float) loc.getX(), (float) loc.getY(), (float) loc.getZ(), (float) 5, (float) 5, (float) 5, 0.0F, count, 0, 0); + Core.getOnlinePlayers().stream().filter(CustomPlayer::hasEffects).forEach(p -> p.getHandle().playerConnection.sendPacket(packet)); } public static void playEffectToPlayer(Player p, Location loc, EnumParticle ep, float f, int count) { diff --git a/src/main/java/eu/univento/core/api/effects/ParticleEffect.java b/src/main/java/eu/univento/core/api/effects/ParticleEffect.java index 14c4e9e..b83e868 100644 --- a/src/main/java/eu/univento/core/api/effects/ParticleEffect.java +++ b/src/main/java/eu/univento/core/api/effects/ParticleEffect.java @@ -384,8 +384,8 @@ public enum ParticleEffect { */ MOB_APPEARANCE("mobappearance", 41, 8); - private static final Map NAME_MAP = new HashMap(); - private static final Map ID_MAP = new HashMap(); + private static final Map NAME_MAP = new HashMap<>(); + private static final Map ID_MAP = new HashMap<>(); private final String name; private final int id; private final int requiredVersion; @@ -407,7 +407,7 @@ public enum ParticleEffect { * @param requiredVersion Version which is required (1.x) * @param properties Properties of this particle effect */ - private ParticleEffect(String name, int id, int requiredVersion, ParticleProperty... properties) { + ParticleEffect(String name, int id, int requiredVersion, ParticleProperty... properties) { this.name = name; this.id = id; this.requiredVersion = requiredVersion; @@ -419,7 +419,7 @@ public enum ParticleEffect { * * @return The name */ - public String getName() { + private String getName() { return name; } @@ -428,7 +428,7 @@ public enum ParticleEffect { * * @return The id */ - public int getId() { + private int getId() { return id; } @@ -446,7 +446,7 @@ public enum ParticleEffect { * * @return Whether it has the property or not */ - public boolean hasProperty(ParticleProperty property) { + private boolean hasProperty(ParticleProperty property) { return properties.contains(property); } @@ -455,7 +455,7 @@ public enum ParticleEffect { * * @return Whether the particle effect is supported or not */ - public boolean isSupported() { + private boolean isSupported() { if (requiredVersion == -1) { return true; } @@ -563,7 +563,7 @@ public enum ParticleEffect { */ public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); + throw new ParticleVersionException(); } if (hasProperty(ParticleProperty.REQUIRES_DATA)) { throw new ParticleDataException("This particle effect requires additional data"); @@ -590,9 +590,9 @@ public enum ParticleEffect { * @see ParticlePacket * @see ParticlePacket#sendTo(Location, List) */ - public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { + private void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); + throw new ParticleVersionException(); } if (hasProperty(ParticleProperty.REQUIRES_DATA)) { throw new ParticleDataException("This particle effect requires additional data"); @@ -637,7 +637,7 @@ public enum ParticleEffect { */ public void display(Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); + throw new ParticleVersionException(); } if (hasProperty(ParticleProperty.REQUIRES_DATA)) { throw new ParticleDataException("This particle effect requires additional data"); @@ -664,9 +664,9 @@ public enum ParticleEffect { * @see ParticlePacket#ParticlePacket(ParticleEffect, Vector, float, boolean, ParticleData) * @see ParticlePacket#sendTo(Location, List) */ - public void display(Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { + private void display(Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); + throw new ParticleVersionException(); } if (hasProperty(ParticleProperty.REQUIRES_DATA)) { throw new ParticleDataException("This particle effect requires additional data"); @@ -709,7 +709,7 @@ public enum ParticleEffect { */ public void display(ParticleColor color, Location center, double range) throws ParticleVersionException, ParticleColorException { if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); + throw new ParticleVersionException(); } if (!hasProperty(ParticleProperty.COLORABLE)) { throw new ParticleColorException("This particle effect is not colorable"); @@ -731,9 +731,9 @@ public enum ParticleEffect { * @see ParticlePacket#ParticlePacket(ParticleEffect, ParticleColor, boolean) * @see ParticlePacket#sendTo(Location, List) */ - public void display(ParticleColor color, Location center, List players) throws ParticleVersionException, ParticleColorException { + private void display(ParticleColor color, Location center, List players) throws ParticleVersionException, ParticleColorException { if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); + throw new ParticleVersionException(); } if (!hasProperty(ParticleProperty.COLORABLE)) { throw new ParticleColorException("This particle effect is not colorable"); @@ -776,7 +776,7 @@ public enum ParticleEffect { */ public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException { if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); + throw new ParticleVersionException(); } if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { throw new ParticleDataException("This particle effect does not require additional data"); @@ -803,9 +803,9 @@ public enum ParticleEffect { * @see ParticlePacket * @see ParticlePacket#sendTo(Location, List) */ - public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException { + private void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException { if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); + throw new ParticleVersionException(); } if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { throw new ParticleDataException("This particle effect does not require additional data"); @@ -850,7 +850,7 @@ public enum ParticleEffect { */ public void display(ParticleData data, Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException { if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); + throw new ParticleVersionException(); } if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { throw new ParticleDataException("This particle effect does not require additional data"); @@ -874,9 +874,9 @@ public enum ParticleEffect { * @see ParticlePacket * @see ParticlePacket#sendTo(Location, List) */ - public void display(ParticleData data, Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException { + private void display(ParticleData data, Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException { if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); + throw new ParticleVersionException(); } if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { throw new ParticleDataException("This particle effect does not require additional data"); @@ -911,7 +911,7 @@ public enum ParticleEffect { * @author DarkBlade12 * @since 1.7 */ - public static enum ParticleProperty { + public enum ParticleProperty { /** * The particle effect requires water to be displayed */ @@ -1001,7 +1001,7 @@ public enum ParticleEffect { * @author DarkBlade12 * @since 1.6 */ - public static final class ItemData extends ParticleData { + private static final class ItemData extends ParticleData { /** * Construct a new item data * @@ -1022,7 +1022,7 @@ public enum ParticleEffect { * @author DarkBlade12 * @since 1.6 */ - public static final class BlockData extends ParticleData { + private static final class BlockData extends ParticleData { /** * Construct a new block data * @@ -1296,11 +1296,10 @@ public enum ParticleEffect { /** * Construct a new particle version exception - * - * @param message Message that will be logged + * */ - public ParticleVersionException(String message) { - super(message); + public ParticleVersionException() { + super("This particle effect is not supported by your server version"); } } @@ -1371,7 +1370,7 @@ public enum ParticleEffect { * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 * @param data Data of the effect * @throws IllegalArgumentException If the speed is lower than 0 - * @see #ParticleEffect(ParticleEffect, float, float, float, float, int, boolean, ParticleData) + * @see (ParticleEffect, float, float, float, float, int, boolean, ParticleData) */ public ParticlePacket(ParticleEffect effect, Vector direction, float speed, boolean longDistance, ParticleData data) throws IllegalArgumentException { this(effect, (float) direction.getX(), (float) direction.getY(), (float) direction.getZ(), speed, 0, longDistance, data); @@ -1383,7 +1382,7 @@ public enum ParticleEffect { * @param effect Particle effect * @param color Color of the particle * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 - * @see #ParticleEffect(ParticleEffect, float, float, float, float, int, boolean, ParticleData) + * @see(ParticleEffect, float, float, float, float, int, boolean, ParticleData) */ public ParticlePacket(ParticleEffect effect, ParticleColor color, boolean longDistance) { this(effect, color.getValueX(), color.getValueY(), color.getValueZ(), 1, 0, longDistance, null); @@ -1411,10 +1410,10 @@ public enum ParticleEffect { Class packetClass = PackageType.MINECRAFT_SERVER.getClass(version < 7 ? "Packet63WorldParticles" : "PacketPlayOutWorldParticles"); packetConstructor = ReflectionUtils.getConstructor(packetClass); getHandle = ReflectionUtils.getMethod("CraftPlayer", PackageType.CRAFTBUKKIT_ENTITY, "getHandle"); - playerConnection = ReflectionUtils.getField("EntityPlayer", PackageType.MINECRAFT_SERVER, false, "playerConnection"); + playerConnection = ReflectionUtils.getField("EntityPlayer", false, "playerConnection"); sendPacket = ReflectionUtils.getMethod(playerConnection.getType(), "sendPacket", PackageType.MINECRAFT_SERVER.getClass("Packet")); } catch (Exception exception) { - throw new VersionIncompatibleException("Your current bukkit version seems to be incompatible with this library", exception); + throw new VersionIncompatibleException(exception); } initialized = true; } @@ -1458,25 +1457,25 @@ public enum ParticleEffect { if (data != null) { name += data.getPacketDataString(); } - ReflectionUtils.setValue(packet, true, "a", name); + ReflectionUtils.setValue(packet, "a", name); } else { - ReflectionUtils.setValue(packet, true, "a", enumParticle.getEnumConstants()[effect.getId()]); - ReflectionUtils.setValue(packet, true, "j", longDistance); + ReflectionUtils.setValue(packet, "a", enumParticle.getEnumConstants()[effect.getId()]); + ReflectionUtils.setValue(packet, "j", longDistance); if (data != null) { int[] packetData = data.getPacketData(); - ReflectionUtils.setValue(packet, true, "k", effect == ParticleEffect.ITEM_CRACK ? packetData : new int[] { packetData[0] | (packetData[1] << 12) }); + ReflectionUtils.setValue(packet, "k", effect == ParticleEffect.ITEM_CRACK ? packetData : new int[] { packetData[0] | (packetData[1] << 12) }); } } - ReflectionUtils.setValue(packet, true, "b", (float) center.getX()); - ReflectionUtils.setValue(packet, true, "c", (float) center.getY()); - ReflectionUtils.setValue(packet, true, "d", (float) center.getZ()); - ReflectionUtils.setValue(packet, true, "e", offsetX); - ReflectionUtils.setValue(packet, true, "f", offsetY); - ReflectionUtils.setValue(packet, true, "g", offsetZ); - ReflectionUtils.setValue(packet, true, "h", speed); - ReflectionUtils.setValue(packet, true, "i", amount); + ReflectionUtils.setValue(packet, "b", (float) center.getX()); + ReflectionUtils.setValue(packet, "c", (float) center.getY()); + ReflectionUtils.setValue(packet, "d", (float) center.getZ()); + ReflectionUtils.setValue(packet, "e", offsetX); + ReflectionUtils.setValue(packet, "f", offsetY); + ReflectionUtils.setValue(packet, "g", offsetZ); + ReflectionUtils.setValue(packet, "h", speed); + ReflectionUtils.setValue(packet, "i", amount); } catch (Exception exception) { - throw new PacketInstantiationException("Packet instantiation failed", exception); + throw new PacketInstantiationException(exception); } } @@ -1550,12 +1549,11 @@ public enum ParticleEffect { /** * Construct a new version incompatible exception - * - * @param message Message that will be logged + * * @param cause Cause of the exception */ - public VersionIncompatibleException(String message, Throwable cause) { - super(message, cause); + public VersionIncompatibleException(Throwable cause) { + super("Your current bukkit version seems to be incompatible with this library", cause); } } @@ -1572,12 +1570,11 @@ public enum ParticleEffect { /** * Construct a new packet instantiation exception - * - * @param message Message that will be logged + * * @param cause Cause of the exception */ - public PacketInstantiationException(String message, Throwable cause) { - super(message, cause); + public PacketInstantiationException(Throwable cause) { + super("Packet instantiation failed", cause); } } diff --git a/src/main/java/eu/univento/core/api/effects/ParticleWorldBoarder.java b/src/main/java/eu/univento/core/api/effects/ParticleWorldBoarder.java new file mode 100644 index 0000000..843c7cd --- /dev/null +++ b/src/main/java/eu/univento/core/api/effects/ParticleWorldBoarder.java @@ -0,0 +1,114 @@ +package eu.univento.core.api.effects; + +import java.util.ArrayList; +import java.util.List; + +import eu.univento.core.api.events.BorderLeaveEvent; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.plugin.Plugin; + +/** + * @author Janhektor + * @version 1.0 + */ + +public class ParticleWorldBoarder implements Listener { + + private Plugin plugin; + private Location center; + private int radius; + private int particleDistance; + private double particlesPerBlock; + private List points; + private ParticleEffect particle; + + public ParticleWorldBoarder() { + + } + + public ParticleWorldBoarder(Plugin plugin, Location center, int radius, ParticleEffect particle) { + this(plugin, center, radius, 15, 2.0D, particle); + } + + public ParticleWorldBoarder(Plugin plugin, Location center, int radius, int particleDistance, double particlesPerBlock, ParticleEffect particle) { + this.plugin = plugin; + this.center = center; + this.radius = radius; + this.particleDistance = particleDistance; + this.particlesPerBlock = particlesPerBlock; + this.points = new ArrayList<>(); + this.particle = particle; + Bukkit.getPluginManager().registerEvents(this, plugin); + + calculatePoints(); + } + + private void calculatePoints() { + points.clear(); + double u = 2 * Math.PI * radius; + double particleCount = u * this.particlesPerBlock; + double degree = 360 / particleCount; + for (double deg = 0; deg <= 360; deg += degree) { + double x = Math.cos(Math.toRadians(deg)); + double z = Math.sin(Math.toRadians(deg)); + points.add(center.clone().add(x * radius, 0, z * radius)); + } + } + + public Location getCenter() { + return center; + } + + public int getRadius() { + return radius; + } + + public int getParticleDistance() { + return particleDistance; + } + + public double getParticlesPerBlock() { + return particlesPerBlock; + } + + public void setRadius(int radius) { + this.radius = radius; + calculatePoints(); + } + + public void setCenter(Location center) { + this.center = center; + calculatePoints(); + } + + public void setParticleDistance(int particleDistance) { + this.particleDistance = particleDistance; + calculatePoints(); + } + + public void setParticlesPerBlock(double particlesPerBlock) { + this.particlesPerBlock = particlesPerBlock; + calculatePoints(); + } + + public boolean isInside(Location loc) { + double a = center.getX() - loc.getX(); + double b = center.getZ() - loc.getZ(); + return a * a + b * b < radius * radius; + } + + @EventHandler + public void playerMoved(PlayerMoveEvent e) { + Player p = e.getPlayer(); + points.stream().filter(loc -> loc.distanceSquared(p.getLocation()) < particleDistance * particleDistance).forEach(loc -> particle.display(0.1F, 0.0F, 0.1F, 0.0F, 1, loc, p)); + + if (isInside(e.getFrom()) && !isInside(e.getTo())) { + Bukkit.getPluginManager().callEvent(new BorderLeaveEvent(p)); + } + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/effects/WorldBoarder.java b/src/main/java/eu/univento/core/api/effects/WorldBoarder.java deleted file mode 100644 index d37eb20..0000000 --- a/src/main/java/eu/univento/core/api/effects/WorldBoarder.java +++ /dev/null @@ -1,129 +0,0 @@ -package eu.univento.core.api.effects; - -import eu.univento.core.Core; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * @author MrSheepSheep - * @version 0.1 - */ -public class WorldBoarder { - - private static Method handle, sendPacket; - private static Method center, distance, time, movement; - private static Field player_connection; - private static Constructor constructor, border_constructor; - private static Object constant; - - static { - try { - handle = getClass("org.bukkit.craftbukkit", "entity.CraftPlayer").getMethod("getHandle"); - player_connection = getClass("net.minecraft.server", "EntityPlayer").getField("playerConnection"); - for (Method m : getClass("net.minecraft.server", "PlayerConnection").getMethods()) { - if (m.getName().equals("sendPacket")) { - sendPacket = m; - break; - } - } - Class enumclass; - try { - enumclass = getClass("net.minecraft.server", "EnumWorldBorderAction"); - } catch(ClassNotFoundException x) { - enumclass = getClass("net.minecraft.server", "PacketPlayOutWorldBorder$EnumWorldBorderAction"); - } - constructor = getClass("net.minecraft.server", "PacketPlayOutWorldBorder").getConstructor(getClass("net.minecraft.server", "WorldBorder"), enumclass); - border_constructor = getClass("net.minecraft.server", "WorldBorder").getConstructor(); - - Method[] methods = getClass("net.minecraft.server", "WorldBorder").getMethods(); - - String setCenter = "setCenter"; - String setWarningDistance = "setWarningDistance"; - String setWarningTime = "setWarningTime"; - String transitionSizeBetween = "transitionSizeBetween"; - - if (!inClass(methods, setCenter)) - setCenter = "c"; - if (!inClass(methods, setWarningDistance)) - setWarningDistance = "c"; - if (!inClass(methods, setWarningTime)) - setWarningTime = "b"; - if (!inClass(methods, transitionSizeBetween)) - transitionSizeBetween = "a"; - - center = getClass("net.minecraft.server", "WorldBorder").getMethod(setCenter, double.class, double.class); - distance = getClass("net.minecraft.server", "WorldBorder").getMethod(setWarningDistance, int.class); - time = getClass("net.minecraft.server", "WorldBorder").getMethod(setWarningTime, int.class); - movement = getClass("net.minecraft.server", "WorldBorder").getMethod(transitionSizeBetween, double.class, double.class, long.class); - - for (Object o: enumclass.getEnumConstants()) { - if (o.toString().equals("INITIALIZE")) { - constant = o; - break; - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private static boolean inClass(Method[] methods, String methodName){ - for (Method m : methods) - if (Objects.equals(m.getName(), methodName)) - return true; - return false; - } - - private static Class getClass(String prefix, String name) throws Exception { - return Class.forName((prefix + ".") + Bukkit.getServer().getClass().getPackage().getName().substring(Bukkit.getServer().getClass().getPackage().getName().lastIndexOf(".") + 1) + "." + name); - } - - Core plugin; - protected List togglelist = new ArrayList<>(); - - protected WorldBoarder(Core plugin) { - this.plugin = plugin; - } - - protected void sendBorder(Player p, int percentage, int intensity){ - percentage = Math.round(percentage / intensity); - setBorder(p, percentage); - fadeBorder(p, percentage, 5); - } - - protected void fadeBorder(Player p, int percentage, long time){ - int dist = -10000 * percentage + 1300000; - sendWorldBorderPacket(p, 0, 200000D, (double) dist, (long) 1000 * time + 4000); //Add 4000 to make sure the "security" zone does not count in the fade time - } - - protected void removeBorder(Player p) { - sendWorldBorderPacket(p, 0, 200000D, 200000D, 0); - } - - protected void setBorder(Player p, int percentage){ - int dist = -10000 * percentage + 1300000; - sendWorldBorderPacket(p, dist, 200000D, 200000D, 0); - } - - protected void sendWorldBorderPacket(Player p, int dist, double oldradius, double newradius, long delay) { - try { - Object worldborder = border_constructor.newInstance(); - center.invoke(worldborder, p.getLocation().getX(), p.getLocation().getY()); - distance.invoke(worldborder, dist); - time.invoke(worldborder, 15); - movement.invoke(worldborder, oldradius, newradius, delay); - - Object packet = constructor.newInstance(worldborder, constant); - sendPacket.invoke(player_connection.get(handle.invoke(p)), packet); - } catch(Exception x) { - x.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/entity/EntityModifier.java b/src/main/java/eu/univento/core/api/entity/EntityModifier.java index 07b6c41..a8cca96 100644 --- a/src/main/java/eu/univento/core/api/entity/EntityModifier.java +++ b/src/main/java/eu/univento/core/api/entity/EntityModifier.java @@ -17,13 +17,13 @@ import java.lang.reflect.Field; * @version 1.0 */ public class EntityModifier { - static org.bukkit.entity.Entity entity; - static CraftEntity craftentity; - static net.minecraft.server.v1_10_R1.Entity entityS; - static int scheduler; - static Plugin plugin; - static Player player = null; - static float Speed; + private static org.bukkit.entity.Entity entity; + private static CraftEntity craftentity; + private static net.minecraft.server.v1_10_R1.Entity entityS; + private static int scheduler; + private static Plugin plugin; + private static Player player = null; + private static float Speed; public EntityModifier(org.bukkit.entity.Entity entity, Plugin plugin) { EntityModifier.entity = entity; @@ -44,7 +44,7 @@ public class EntityModifier { } public Builder setDisplayNameVisible(Boolean visible) { - EntityModifier.entity.setCustomNameVisible(visible.booleanValue()); + EntityModifier.entity.setCustomNameVisible(visible); return this; } @@ -81,9 +81,8 @@ public class EntityModifier { return this; } - public Builder teleport(Location location) { + public void teleport(Location location) { EntityModifier.entity.teleport(location); - return this; } public Builder die() { @@ -171,26 +170,23 @@ public class EntityModifier { EntityModifier.player = target; EntityModifier.Speed = speed; EntityModifier.scheduler = Bukkit.getScheduler().scheduleSyncRepeatingTask(EntityModifier.plugin, - new Runnable() { - @SuppressWarnings("deprecation") - public void run() { - double distance = EntityModifier.entity.getLocation().distance( - EntityModifier.player.getLocation()); - if (distance < 11.0D) { - float speed = EntityModifier.Speed; - if (distance < 3.0D) { - speed = 0.0F; - } - ((CraftCreature) EntityModifier.entity) - .getHandle() - .getNavigation() - .a(EntityModifier.player.getLocation().getX(), - EntityModifier.player.getLocation().getY(), - EntityModifier.player.getLocation().getZ(), - speed); - } else if (EntityModifier.player.isOnGround()) { - EntityModifier.entity.teleport(EntityModifier.player); + () -> { + double distance = EntityModifier.entity.getLocation().distance( + EntityModifier.player.getLocation()); + if (distance < 11.0D) { + float speed1 = EntityModifier.Speed; + if (distance < 3.0D) { + speed1 = 0.0F; } + ((CraftCreature) EntityModifier.entity) + .getHandle() + .getNavigation() + .a(EntityModifier.player.getLocation().getX(), + EntityModifier.player.getLocation().getY(), + EntityModifier.player.getLocation().getZ(), + speed1); + } else if (EntityModifier.player.isOnGround()) { + EntityModifier.entity.teleport(EntityModifier.player); } } , 0L, 1L); diff --git a/src/main/java/eu/univento/core/api/events/BorderLeaveEvent.java b/src/main/java/eu/univento/core/api/events/BorderLeaveEvent.java new file mode 100644 index 0000000..c655169 --- /dev/null +++ b/src/main/java/eu/univento/core/api/events/BorderLeaveEvent.java @@ -0,0 +1,31 @@ +package eu.univento.core.api.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +/** + * @author Janhektor + * @version 1.0 + */ + +public class BorderLeaveEvent extends PlayerEvent { + + public BorderLeaveEvent(Player who) { + super(who); + } + public static HandlerList handlers; + + static { + handlers = new HandlerList(); + } + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/src/main/java/eu/univento/core/api/events/MoveEventFilter.java b/src/main/java/eu/univento/core/api/events/MoveEventFilter.java index fb64b9c..3f9a00d 100644 --- a/src/main/java/eu/univento/core/api/events/MoveEventFilter.java +++ b/src/main/java/eu/univento/core/api/events/MoveEventFilter.java @@ -27,8 +27,8 @@ public class MoveEventFilter implements Listener { public World world; } - private Server mServer; - private WeakHashMap mLastPosition = new WeakHashMap<>(); + private final Server mServer; + private final WeakHashMap mLastPosition = new WeakHashMap<>(); public MoveEventFilter(Server pServer) { mServer = pServer; diff --git a/src/main/java/eu/univento/core/api/fakeplayer/FakePlayer.java b/src/main/java/eu/univento/core/api/fakeplayer/FakePlayer.java index 60f0964..c4aad6c 100644 --- a/src/main/java/eu/univento/core/api/fakeplayer/FakePlayer.java +++ b/src/main/java/eu/univento/core/api/fakeplayer/FakePlayer.java @@ -24,17 +24,17 @@ public class FakePlayer { private static final double MOVE_SPEED = 4.3D / 20; - private Player player; - private int entityId; - private GameProfile gameProfile; - private DataWatcher dataWatcher; + private final Player player; + private final int entityId; + private final GameProfile gameProfile; + private final DataWatcher dataWatcher; private Location location; private ArmorStand armorStand; private LivingEntity target; private BukkitTask task; - private boolean moveable; + private final boolean moveable; public FakePlayer(GameProfile gameProfile, boolean moveable, Player player) { @@ -42,7 +42,7 @@ public class FakePlayer { this.moveable = moveable; - this.entityId = (int) get(Entity.class, null, "entityCount"); + this.entityId = (int) get(Entity.class, "entityCount"); set(Entity.class, null, "entityCount", this.entityId + 1); this.gameProfile = gameProfile; @@ -75,13 +75,14 @@ public class FakePlayer { } }; + /* private byte changeMask(byte bitMask, int bit, boolean state) { if(state) - return bitMask |= 1 << bit; + return bitMask | 1 << bit; else - return bitMask &= ~(1 << bit); - + return bitMask & ~(1 << bit); } + */ public void setTarget(LivingEntity target) { this.target = target; @@ -95,8 +96,8 @@ public class FakePlayer { setStatus(0, fire); } - public void setSneaking(boolean sneaking) { - setStatus(1, sneaking); + public void setSneaking() { + setStatus(1, true); } public void setSprinting(boolean sprinting) { @@ -114,7 +115,6 @@ public class FakePlayer { private void setStatus(int data, boolean bool) { DataWatcher dataWatcher = this.dataWatcher; byte status = 0; - status = changeMask(status, data, bool); //dataWatcher.a(0, status); //dataWatcher.a(10, (byte) 127); //dataWatcher.a(6, 20F); @@ -134,14 +134,14 @@ public class FakePlayer { yaw = (float) Math.toRadians(yaw); double x = Math.sin(yaw); double z = Math.cos(yaw); - move(x * MOVE_SPEED, 0, z * MOVE_SPEED); + move(x * MOVE_SPEED, z * MOVE_SPEED); } } } - private void move(double x, int y, double z) { - sendPackets(new PacketPlayOutEntity.PacketPlayOutRelEntityMoveLook(this.entityId, (byte) toFixedPointNumber(x), (byte) toFixedPointNumber(y), (byte) toFixedPointNumber(z), toAngle(location.getYaw()), toAngle(location.getPitch()), true)); - this.location.add(toFixedPointNumber(x) / 32D, toFixedPointNumber(y) / 32D, toFixedPointNumber(z) / 32D); + private void move(double x, double z) { + sendPackets(new PacketPlayOutEntity.PacketPlayOutRelEntityMoveLook(this.entityId, (byte) toFixedPointNumber(x), (byte) toFixedPointNumber(0), (byte) toFixedPointNumber(z), toAngle(location.getYaw()), toAngle(location.getPitch()), true)); + this.location.add(toFixedPointNumber(x) / 32D, toFixedPointNumber(0) / 32D, toFixedPointNumber(z) / 32D); this.armorStand.teleport(this.location); } @@ -205,7 +205,7 @@ public class FakePlayer { return (byte) ((int) (value * 256.0F / 360.F)); } - public void sendPackets(Packet... packets) { + private void sendPackets(Packet... packets) { for(Packet packet : packets) ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); } @@ -224,11 +224,11 @@ public class FakePlayer { } } - private Object get(Class clazz, Object instance, String name) { + private Object get(Class clazz, String name) { try{ - Field field = clazz.getDeclaredField(name); + Field field = clazz.getDeclaredField("entityCount"); field.setAccessible(true); - return field.get(instance); + return field.get(null); }catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/eu/univento/core/api/fakeplayer/PlayerKi.java b/src/main/java/eu/univento/core/api/fakeplayer/PlayerKi.java index 4661219..87c88f6 100644 --- a/src/main/java/eu/univento/core/api/fakeplayer/PlayerKi.java +++ b/src/main/java/eu/univento/core/api/fakeplayer/PlayerKi.java @@ -15,12 +15,12 @@ import java.util.UUID; * @author joethei * @version 0.1 */ -public class PlayerKi implements Listener{ +class PlayerKi implements Listener{ - FakePlayer player; + private FakePlayer player; - public FakePlayer createPlayer(Player p, String uuid, String name, String skinUrl, String capeUrl) { - GameProfile gameProfile = GameProfileBuilder.getProfile(UUID.fromString(uuid), name, skinUrl, capeUrl); + private FakePlayer createPlayer(Player p, String uuid, String skinUrl, String capeUrl) { + GameProfile gameProfile = GameProfileBuilder.getProfile(UUID.fromString(uuid), "TestUser", skinUrl, capeUrl); return new FakePlayer(gameProfile, true, p); } @@ -32,12 +32,12 @@ public class PlayerKi implements Listener{ this.player.despawn(); } FakePlayer player = createPlayer(e.getPlayer(), e.getPlayer().getUniqueId().toString(), - "TestUser", "http://textures.minecraft.net/texture/a116e69a845e227f7ca1fdde8c357c8c821ebd4ba619382ea4a1f87d4ae94", + "http://textures.minecraft.net/texture/a116e69a845e227f7ca1fdde8c357c8c821ebd4ba619382ea4a1f87d4ae94", "http://textures.minecraft.net/texture/3f688e0e699b3d9fe448b5bb50a3a288f9c589762b3dae8308842122dcb81"); this.player = player; player.spawn(e.getPlayer().getLocation()); player.setTarget(e.getPlayer()); - player.setSneaking(true); + player.setSneaking(); player.removeTablist(); } if(e.getItem().getType() == Material.DIAMOND_SWORD) { diff --git a/src/main/java/eu/univento/core/api/game/PlayerManager.java b/src/main/java/eu/univento/core/api/game/PlayerManager.java new file mode 100644 index 0000000..0532b74 --- /dev/null +++ b/src/main/java/eu/univento/core/api/game/PlayerManager.java @@ -0,0 +1,37 @@ +package eu.univento.core.api.game; + +import eu.univento.core.api.player.CustomPlayer; + +import java.util.LinkedList; +import java.util.List; + +/** + * @author joethei + * @version 0.1 + * Created at 00:00 on 18.07.2016. + */ +public class PlayerManager { + + private static final List players = new LinkedList<>(); + + + public static List getPlayers() { + return players; + } + + public static void add(CustomPlayer p) { + players.add(p); + } + + public static void remove(CustomPlayer p) { + if(players.contains(p)) players.remove(p); + } + + public static boolean contains(CustomPlayer p) { + return players.contains(p); + } + + public static int size() { + return getPlayers().size(); + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/game/Team.java b/src/main/java/eu/univento/core/api/game/Team.java index 43e9fb6..c0e1bc6 100644 --- a/src/main/java/eu/univento/core/api/game/Team.java +++ b/src/main/java/eu/univento/core/api/game/Team.java @@ -11,10 +11,10 @@ import java.util.ArrayList; */ public class Team { - private ArrayList players = new ArrayList<>(); - private String name; - private String prefix; - private org.bukkit.scoreboard.Team team; + private final ArrayList players = new ArrayList<>(); + private final String name; + private final String prefix; + private final org.bukkit.scoreboard.Team team; public Team(String name, String prefix) { this.name = name; diff --git a/src/main/java/eu/univento/core/api/game/TeamManager.java b/src/main/java/eu/univento/core/api/game/TeamManager.java index f9d5b15..84a7a46 100644 --- a/src/main/java/eu/univento/core/api/game/TeamManager.java +++ b/src/main/java/eu/univento/core/api/game/TeamManager.java @@ -8,9 +8,9 @@ import java.util.ArrayList; * @author joethei * @version 0.1 */ -public class TeamManager { +class TeamManager { - private static ArrayList teams = new ArrayList<>(); + private static final ArrayList teams = new ArrayList<>(); public static ArrayList getTeams() { return teams; diff --git a/src/main/java/eu/univento/core/api/gui/AnvilGUI.java b/src/main/java/eu/univento/core/api/gui/AnvilGUI.java index 08741b5..60642a0 100644 --- a/src/main/java/eu/univento/core/api/gui/AnvilGUI.java +++ b/src/main/java/eu/univento/core/api/gui/AnvilGUI.java @@ -37,9 +37,9 @@ public class AnvilGUI { INPUT_RIGHT(1), OUTPUT(2); - private int slot; + private final int slot; - private AnvilSlot(int slot){ + AnvilSlot(int slot){ this.slot = slot; } @@ -59,9 +59,9 @@ public class AnvilGUI { } public class AnvilClickEvent { - private AnvilSlot slot; + private final AnvilSlot slot; - private String name; + private final String name; private boolean close = true; private boolean destroy = true; @@ -83,28 +83,28 @@ public class AnvilGUI { return close; } - public void setWillClose(boolean close){ - this.close = close; + public void setWillClose(){ + this.close = true; } public boolean getWillDestroy(){ return destroy; } - public void setWillDestroy(boolean destroy){ - this.destroy = destroy; + public void setWillDestroy(){ + this.destroy = true; } } public interface AnvilClickEventHandler { - public void onAnvilClick(AnvilClickEvent event); + void onAnvilClick(AnvilClickEvent event); } private Player player; private AnvilClickEventHandler handler; - private HashMap items = new HashMap(); + private HashMap items = new HashMap<>(); private Inventory inv; @@ -118,7 +118,6 @@ public class AnvilGUI { @EventHandler public void onInventoryClick(InventoryClickEvent event){ if(event.getWhoClicked() instanceof Player){ - Player clicker = (Player) event.getWhoClicked(); if(event.getInventory().equals(inv)){ event.setCancelled(true); @@ -155,7 +154,6 @@ public class AnvilGUI { @EventHandler public void onInventoryClose(InventoryCloseEvent event){ if(event.getPlayer() instanceof Player){ - Player player = (Player) event.getPlayer(); Inventory inv = event.getInventory(); if(inv.equals(AnvilGUI.this.inv)){ @@ -176,12 +174,12 @@ public class AnvilGUI { Bukkit.getPluginManager().registerEvents(listener, Core.getInstance()); //Replace with instance of main class } - public Player getPlayer(){ + private Player getPlayer(){ return player; } - public void setSlot(AnvilSlot slot, ItemStack item){ - items.put(slot, item); + public void setSlot(ItemStack item){ + items.put(AnvilSlot.INPUT_LEFT, item); } public void open(){ @@ -200,7 +198,7 @@ public class AnvilGUI { int c = p.nextContainerCounter(); //Send the packet - p.playerConnection.sendPacket(new PacketPlayOutOpenWindow(c, "minecraft:anvil", new ChatMessage("Repairing", new Object[]{}), 0)); + p.playerConnection.sendPacket(new PacketPlayOutOpenWindow(c, "minecraft:anvil", new ChatMessage("Repairing"), 0)); //Set their active container to the container p.activeContainer = container; @@ -212,7 +210,7 @@ public class AnvilGUI { p.activeContainer.addSlotListener(p); } - public void destroy(){ + private void destroy(){ player = null; handler = null; items = null; diff --git a/src/main/java/eu/univento/core/api/gui/PlayerSignInputEvent.java b/src/main/java/eu/univento/core/api/gui/PlayerSignInputEvent.java index fb78412..a79e9b3 100644 --- a/src/main/java/eu/univento/core/api/gui/PlayerSignInputEvent.java +++ b/src/main/java/eu/univento/core/api/gui/PlayerSignInputEvent.java @@ -8,10 +8,10 @@ import org.bukkit.event.player.PlayerEvent; * @author joethei * @version 0.1 */ -public class PlayerSignInputEvent extends PlayerEvent{ +class PlayerSignInputEvent extends PlayerEvent{ - public static HandlerList handlerList = new HandlerList(); - public String[] lines; + private static final HandlerList handlerList = new HandlerList(); + private final String[] lines; public PlayerSignInputEvent(Player p, String[] lines) { super(p); diff --git a/src/main/java/eu/univento/core/api/gui/SignInput.java b/src/main/java/eu/univento/core/api/gui/SignInput.java index 71c938b..3217d51 100644 --- a/src/main/java/eu/univento/core/api/gui/SignInput.java +++ b/src/main/java/eu/univento/core/api/gui/SignInput.java @@ -9,7 +9,7 @@ import net.minecraft.server.v1_10_R1.PacketPlayOutOpenSignEditor; * @author joethei * @version 0.1 */ -public class SignInput { +class SignInput { public static void openSignInput(CustomPlayer p) { EntityPlayer player = p.getHandle(); diff --git a/src/main/java/eu/univento/core/api/gui/SignInputHandler.java b/src/main/java/eu/univento/core/api/gui/SignInputHandler.java index 9e9fc7f..70cffc5 100644 --- a/src/main/java/eu/univento/core/api/gui/SignInputHandler.java +++ b/src/main/java/eu/univento/core/api/gui/SignInputHandler.java @@ -17,9 +17,9 @@ import java.util.List; * @author joethei * @version 0.1 */ -public class SignInputHandler { +class SignInputHandler { - private static Field channelField; + private static Field channelField = null; static{ for(Field filed : NetworkManager.class.getDeclaredFields()) { diff --git a/src/main/java/eu/univento/core/api/items/ItemBuilder.java b/src/main/java/eu/univento/core/api/items/ItemBuilder.java index e68767e..e721935 100644 --- a/src/main/java/eu/univento/core/api/items/ItemBuilder.java +++ b/src/main/java/eu/univento/core/api/items/ItemBuilder.java @@ -149,14 +149,16 @@ public class ItemBuilder { /** * Changes the durability of the current {@link ItemStack} * - * @param durability - * the new int amount to set the ItemStack's durability to. - * * @return the current instance for chainable application. * @since 1.0 */ - public ItemBuilder durability(final int durability){ - make().setDurability((short) durability); + public ItemBuilder durability(){ + make().setDurability((short) 3); + return this; + } + + public ItemBuilder durability(short durability) { + make().setDurability(durability); return this; } @@ -360,7 +362,7 @@ public class ItemBuilder { * * @return the ItemMeta of the ItemStack. */ - public ItemMeta meta(){ + private ItemMeta meta(){ return itemM; } diff --git a/src/main/java/eu/univento/core/api/items/ItemSkulls.java b/src/main/java/eu/univento/core/api/items/ItemSkulls.java deleted file mode 100644 index 4c7e679..0000000 --- a/src/main/java/eu/univento/core/api/items/ItemSkulls.java +++ /dev/null @@ -1,105 +0,0 @@ -package eu.univento.core.api.items; - -import com.mojang.authlib.GameProfile; -import com.mojang.authlib.properties.Property; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.SkullMeta; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Base64; -import java.util.UUID; - -public class ItemSkulls { - private static Class skullMetaClass; - private static Class tileEntityClass; - private static Class blockPositionClass; - private static int mcVersion; - - static { - String version = org.bukkit.Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; - mcVersion = Integer.parseInt(version.replaceAll("[^0-9]", "")); - try { - skullMetaClass = Class.forName("org.bukkit.craftbukkit." + version + ".inventory.CraftMetaSkull"); - tileEntityClass = Class.forName("net.minecraft.server." + version + ".TileEntitySkull"); - if (mcVersion > 174) - blockPositionClass = Class.forName("net.minecraft.server." + version + ".BlockPosition"); - else - blockPositionClass = null; - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } - - public static ItemStack getSkull(String skinURL) { - return getSkull(skinURL, 1); - } - - public static ItemStack getSkull(String skinURL, int amount) { - ItemStack skull = new ItemStack(Material.SKULL_ITEM, amount, (short) 3); - SkullMeta meta = (SkullMeta) skull.getItemMeta(); - try { - Field profileField = skullMetaClass.getDeclaredField("profile"); - profileField.setAccessible(true); - profileField.set(meta, getProfile(skinURL)); - } catch (Exception ex) { - ex.printStackTrace(); - } - skull.setItemMeta(meta); - return skull; - } - - public static boolean setBlock(Location loc, String skinURL) { - return setBlock(loc.getBlock(), skinURL); - } - - public static boolean setBlock(Block block, String skinURL) { - boolean flag = block.getType() == Material.SKULL; - if (!flag) - block.setType(Material.SKULL); - try { - Object nmsWorld = block.getWorld().getClass().getMethod("getHandle", new Class[0]).invoke(block.getWorld()); - Object tileEntity = null; - - if (mcVersion <= 174) { - Method getTileEntity = nmsWorld.getClass().getMethod("getTileEntity", Integer.TYPE, Integer.TYPE, Integer.TYPE); - tileEntity = tileEntityClass.cast(getTileEntity.invoke(nmsWorld, block.getX(), block.getY(), block.getZ())); - } else { - Method getTileEntity = nmsWorld.getClass().getMethod("getTileEntity", blockPositionClass); - tileEntity = tileEntityClass.cast(getTileEntity.invoke( - nmsWorld, getBlockPositionFor(block.getX(), block.getY(), - block.getZ()))); - } - - tileEntityClass.getMethod("setGameProfile", new Class[]{GameProfile.class}) - .invoke(tileEntity, getProfile(skinURL)); - } catch (Exception ex) { - ex.printStackTrace(); - } - return !flag; - } - - private static GameProfile getProfile(String skinURL) { - GameProfile profile = new GameProfile(UUID.randomUUID(), null); - String base64encoded = Base64.getEncoder().encodeToString( - ("{textures:{SKIN:{url:\"" + skinURL + "\"}}}").getBytes()); - Property property = new Property("textures", base64encoded); - profile.getProperties().put("textures", property); - return profile; - } - - private static Object getBlockPositionFor(int x, int y, int z) { - Object blockPosition = null; - try { - Constructor cons = blockPositionClass.getConstructor(Integer.TYPE, Integer.TYPE, Integer.TYPE); - blockPosition = cons.newInstance(x, y, z); - } catch (Exception ex) { - ex.printStackTrace(); - } - return blockPosition; - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/items/Pagifier.java b/src/main/java/eu/univento/core/api/items/Pagifier.java index 8899d3a..f7b5243 100644 --- a/src/main/java/eu/univento/core/api/items/Pagifier.java +++ b/src/main/java/eu/univento/core/api/items/Pagifier.java @@ -12,11 +12,11 @@ import java.util.Optional; * @author leNic * @version 1.0 */ - public class Pagifier { +class Pagifier { // Properties - private int pageSize; + private final int pageSize; // List of pages - private List> pages; + private final List> pages; // Constructor public Pagifier(int pageSize){ this.pageSize = pageSize; diff --git a/src/main/java/eu/univento/core/api/items/ScrollingInventory.java b/src/main/java/eu/univento/core/api/items/ScrollingInventory.java index 3a93320..db7a8bf 100644 --- a/src/main/java/eu/univento/core/api/items/ScrollingInventory.java +++ b/src/main/java/eu/univento/core/api/items/ScrollingInventory.java @@ -16,25 +16,24 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.util.ArrayList; -import java.util.logging.Level; public class ScrollingInventory implements Listener{ - private Inventory inv; - private ArrayList items = new ArrayList<>(); + private final Inventory inv; + private final ArrayList items = new ArrayList<>(); private ItemStack next; private ItemStack back; private int side = 0; private int rows = 4; - private CustomPlayer player; - public ScrollingInventory(CustomPlayer player, String name, int rows){ + private final CustomPlayer player; + public ScrollingInventory(CustomPlayer player, String name){ this.player = player; int var = 1; - for(int i = 0; i> rows * 9; i = i + 9) + for(int i = 0; i > 27 * 9; i = i + 9) var++; inv = Bukkit.createInventory(player, var * 9 + 9, name); Bukkit.getPluginManager().registerEvents(this, Core.getInstance()); - this.rows = rows; + this.rows = 27; side = 0; } public void addItem(ItemStack item){ diff --git a/src/main/java/eu/univento/core/api/languages/Language.java b/src/main/java/eu/univento/core/api/languages/Language.java index 089ec03..cee0b7a 100644 --- a/src/main/java/eu/univento/core/api/languages/Language.java +++ b/src/main/java/eu/univento/core/api/languages/Language.java @@ -8,13 +8,13 @@ import java.util.ResourceBundle; public class Language { - private ResourceBundle translation; + private final ResourceBundle translation; public Language(String language) { Map languages = new HashMap<>(); languages.put("DE", Locale.GERMAN); languages.put("EN", Locale.ENGLISH); - languages.put("IT", Locale.ITALY); + languages.put("IT", Locale.ITALIAN); translation = ResourceBundle.getBundle("language", languages.get(language)); } diff --git a/src/main/java/eu/univento/core/api/languages/Languages.java b/src/main/java/eu/univento/core/api/languages/Languages.java index 2507f5c..4a0e35f 100644 --- a/src/main/java/eu/univento/core/api/languages/Languages.java +++ b/src/main/java/eu/univento/core/api/languages/Languages.java @@ -7,7 +7,7 @@ import eu.univento.core.api.player.Rank; * @author joethei * @version 0.3 */ -public interface Languages{ +interface Languages{ String UNKNOWN_ERROR(); String NO_PERMS(); diff --git a/src/main/java/eu/univento/core/api/languages/Messages.java b/src/main/java/eu/univento/core/api/languages/Messages.java index 24ebf99..2830693 100644 --- a/src/main/java/eu/univento/core/api/languages/Messages.java +++ b/src/main/java/eu/univento/core/api/languages/Messages.java @@ -10,14 +10,15 @@ import eu.univento.core.api.player.Rank; */ public class Messages { - CustomPlayer player; + private final CustomPlayer player; - Language_DE de = new Language_DE(); - Language_EN en = new Language_EN(); - Language_IT it = new Language_IT(); + private final Language_DE de = new Language_DE(); + private final Language_EN en = new Language_EN(); + private final Language_IT it = new Language_IT(); - Languages lang; + private Languages lang; + @Deprecated public Messages(CustomPlayer player) { this.player = player; if(player.getLanguage().equals("DE")) this.lang = de; @@ -304,11 +305,11 @@ public class Messages { public String LobbyBoard_FORUM() { return lang.LobbyBoard_FORUM(); } public String LobbyBoard_FOUND_SECRETS() { return lang.LobbyBoard_FOUND_SECRETS(); } - public class Build { + private class Build { public String PREFIX = "• §bTeam§3Vento • "; } public static class Console{ - public static String NOT_A_PLAYER = "You are not a valid player"; + public static final String NOT_A_PLAYER = "You are not a valid player"; } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/map/Cuboid.java b/src/main/java/eu/univento/core/api/map/Cuboid.java index 908ab67..21232bc 100644 --- a/src/main/java/eu/univento/core/api/map/Cuboid.java +++ b/src/main/java/eu/univento/core/api/map/Cuboid.java @@ -19,7 +19,7 @@ public class Cuboid implements Cloneable, ConfigurationSerializable, Iterable getAllMaps(Game game) { + public static ArrayList getAllMaps(ServerType serverType) { ArrayList maps = new ArrayList<>(); maps.add(new Map("Map1", "TeamVento", Material.GRASS, "http://creppy.univento.eu/maps/Strive/Map1")); diff --git a/src/main/java/eu/univento/core/api/map/MapDownloader.java b/src/main/java/eu/univento/core/api/map/MapDownloader.java index a16ad79..3578b5e 100644 --- a/src/main/java/eu/univento/core/api/map/MapDownloader.java +++ b/src/main/java/eu/univento/core/api/map/MapDownloader.java @@ -13,7 +13,7 @@ import java.util.logging.Level; * @author joethei * @version 0.1 */ -public class MapDownloader { +class MapDownloader { public static void download(URL file, File dest) { try { diff --git a/src/main/java/eu/univento/core/api/map/MapVoting.java b/src/main/java/eu/univento/core/api/map/MapVoting.java index c31dbc0..d3696d7 100644 --- a/src/main/java/eu/univento/core/api/map/MapVoting.java +++ b/src/main/java/eu/univento/core/api/map/MapVoting.java @@ -20,24 +20,24 @@ import java.util.Random; * @author joethei * @version 0.1 */ -public class MapVoting implements Listener{ +class MapVoting implements Listener{ private Map map1; private Map map2; private Map map3; - private String invTitle; - private ArrayList votes1 = new ArrayList<>(); - private ArrayList votes2 = new ArrayList<>(); - private ArrayList votes3 = new ArrayList<>(); + private final String invTitle; + private final ArrayList votes1 = new ArrayList<>(); + private final ArrayList votes2 = new ArrayList<>(); + private final ArrayList votes3 = new ArrayList<>(); private Map forcedMap; - private ArrayList allMaps = new ArrayList<>(); + private final ArrayList allMaps = new ArrayList<>(); public MapVoting(String invTitle) { this.invTitle = invTitle; } - public void vote(CustomPlayer p, Integer map) { + private void vote(CustomPlayer p, Integer map) { switch (map) { case 1 : votes1.add(p); case 2 : votes2.add(p); @@ -70,7 +70,7 @@ public class MapVoting implements Listener{ return getMap(getMapID(max)); } - public Map getMap(int id) { + private Map getMap(int id) { switch (id) { case 1: return map1; case 2: return map2; @@ -79,7 +79,7 @@ public class MapVoting implements Listener{ } } - public int getMapID(int votes) { + private int getMapID(int votes) { if(votes == votes1.size()) { return 1; } @@ -165,9 +165,7 @@ public class MapVoting implements Listener{ CustomPlayer p = CustomPlayer.getPlayer(e.getWhoClicked().getName()); if(e.getInventory().getName().equals(invTitle)) { if(p.isAllowed(Rank.Admin)) { - allMaps.stream().filter(map -> e.getCurrentItem().getType() == map.getItem()).forEach(map -> { - forcedMap = map; - }); + allMaps.stream().filter(map -> e.getCurrentItem().getType() == map.getItem()).forEach(map -> forcedMap = map); }else{ if(e.getCurrentItem().getType() == map1.getItem()) { vote(p, 1); diff --git a/src/main/java/eu/univento/core/api/pet/NMSHandler.java b/src/main/java/eu/univento/core/api/pet/NMSHandler.java index 0b2c025..4f23bf2 100644 --- a/src/main/java/eu/univento/core/api/pet/NMSHandler.java +++ b/src/main/java/eu/univento/core/api/pet/NMSHandler.java @@ -20,7 +20,6 @@ public class NMSHandler { public static LivingEntity spawn(EntityType type, Location loc) { World nmsWorld = ((CraftWorld) loc.getWorld()).getHandle(); PetType petType = PetType.valueOf(type); - if(petType == null) return null; Entity entity; try { entity = (Entity) petType.getCustomClass().getConstructors()[0].newInstance(nmsWorld); diff --git a/src/main/java/eu/univento/core/api/pet/PetType.java b/src/main/java/eu/univento/core/api/pet/PetType.java index bd3976e..480f0d4 100644 --- a/src/main/java/eu/univento/core/api/pet/PetType.java +++ b/src/main/java/eu/univento/core/api/pet/PetType.java @@ -21,11 +21,11 @@ public enum PetType { CREEPER("Creeper", 50, EntityType.CREEPER, EntityCreeper.class, CustomCreeper.class), PIG("Pig", 90, EntityType.PIG, EntityPig.class, CustomPig.class); - private String name; - private int id; - private EntityType type; - private Class nmsClass; - private Class customClass; + private final String name; + private final int id; + private final EntityType type; + private final Class nmsClass; + private final Class customClass; PetType(String name, int id, EntityType type, Class nmsClass, Class customClass) { this.name = name; @@ -35,19 +35,19 @@ public enum PetType { this.customClass = customClass; } - public String getName() { + private String getName() { return name; } - public int getID() { + private int getID() { return id; } - public EntityType getType() { + private EntityType getType() { return type; } - public Class getNmsClass() { + private Class getNmsClass() { return nmsClass; } diff --git a/src/main/java/eu/univento/core/api/pet/custom/CustomPig.java b/src/main/java/eu/univento/core/api/pet/custom/CustomPig.java index 1531db0..d200793 100644 --- a/src/main/java/eu/univento/core/api/pet/custom/CustomPig.java +++ b/src/main/java/eu/univento/core/api/pet/custom/CustomPig.java @@ -24,7 +24,7 @@ public class CustomPig extends EntityPig{ rideSpeed = 0.5; sideways = 0.5; backwards = 0.25; - stepHeight = 1.0; + stepHeight = 2.0; } @Override diff --git a/src/main/java/eu/univento/core/api/player/BetterPvP.java b/src/main/java/eu/univento/core/api/player/BetterPvP.java index 1ed9bda..4c6bfd2 100644 --- a/src/main/java/eu/univento/core/api/player/BetterPvP.java +++ b/src/main/java/eu/univento/core/api/player/BetterPvP.java @@ -5,56 +5,6 @@ public class BetterPvP { public BetterPvP() { } - private boolean minimap = false; - private boolean armourStatus = true; - private boolean potionStatus = true; - private boolean archeryStatus = true; - private boolean notifications = true; - private boolean xpDrops = true; - private boolean betterSprint = true; - private boolean toggleSneak = true; - private boolean quickItemUse = true; - private boolean armourStatusShowEnchants = true; - private boolean minimapDisplayPlayers = false; - private boolean minimapDisplayMobs =false; - private boolean minimapDisplayItems = false; - private boolean minimapDisplayOther = false; - private boolean caveMaps = false; - private boolean minimapDisplayOtherTeam = false; - private boolean minimapDisplayWaypoints = false; - private boolean notificationHunger = true; - private boolean notificationHp = false; - private boolean notificationTnt = false; - private boolean notificationArrow = false; - private boolean deathpoints = true; - private boolean notificationAir = true; - private boolean entityInfo = true; - - private int minimapMask = 1; - private int armourStatusMask = 2; - private int potionStatusMask = 4; - private int archeryStatusMask = 8; - private int notificationsMask = 16; - private int xpDropsMask = 32; - private int betterSprintMask = 64; - private int toggleSneakMask = 128; - private int quickItemUseMask = 256; - private int armourStatusShowEnchantsMask = 512; - private int minimapDisplayPlayersMask = 1024; - private int minimapDisplayMobsMask = 2048; - private int minimapDisplayItemsMask = 4096; - private int minimapDisplayOtherMask = 8192; - private int caveMapsMask = 16384; - private int minimapDisplayOtherTeamMask = 32768; - private int minimapDisplayWaypointsMask = 65536; - private int notificationHungerMask = 131072; - private int notificationHpMask = 262144; - private int notificationTntMask = 524288; - private int notificationArrowMask = 1048576; - private int deathpointsMask = 2097152; - private int notificationAirMask = 4194304; - private int entityInfoMask = 8388608; - public String getCodeString() { String toReturn = "§c §r§5 §r§1 §r§f"; String code = String.valueOf(getCodeToSend()); @@ -68,30 +18,43 @@ public class BetterPvP { private int getCodeToSend() { int code = 0; - code |= (minimap ? minimapMask : 0); - code |= (armourStatus ? armourStatusMask : 0); - code |= (potionStatus ? potionStatusMask : 0); - code |= (archeryStatus ? archeryStatusMask : 0); - code |= (notifications ? notificationsMask : 0); - code |= (xpDrops ? xpDropsMask : 0); - code |= (betterSprint ? betterSprintMask : 0); - code |= (toggleSneak ? toggleSneakMask : 0); - code |= (quickItemUse ? quickItemUseMask : 0); - code |= (armourStatusShowEnchants ? armourStatusShowEnchantsMask : 0); - code |= (minimapDisplayPlayers ? minimapDisplayPlayersMask : 0); - code |= (minimapDisplayMobs ? minimapDisplayMobsMask : 0); - code |= (minimapDisplayItems ? minimapDisplayItemsMask : 0); - code |= (minimapDisplayOther ? minimapDisplayOtherMask : 0); - code |= (caveMaps ? caveMapsMask : 0); - code |= (minimapDisplayOtherTeam ? minimapDisplayOtherTeamMask : 0); - code |= (minimapDisplayWaypoints ? minimapDisplayWaypointsMask : 0); - code |= (notificationHunger ? notificationHungerMask : 0); - code |= (notificationHp ? notificationHpMask : 0); - code |= (notificationTnt ? notificationTntMask : 0); - code |= (notificationArrow ? notificationArrowMask : 0); - code |= (deathpoints ? deathpointsMask : 0); - code |= (notificationAir ? notificationAirMask : 0); - code |= (entityInfo ? entityInfoMask : 0); + code |= 0; + int armourStatusMask = 2; + code |= armourStatusMask; + int potionStatusMask = 4; + code |= potionStatusMask; + int archeryStatusMask = 8; + code |= archeryStatusMask; + int notificationsMask = 16; + code |= notificationsMask; + int xpDropsMask = 32; + code |= xpDropsMask; + int betterSprintMask = 64; + code |= betterSprintMask; + int toggleSneakMask = 128; + code |= toggleSneakMask; + int quickItemUseMask = 256; + code |= quickItemUseMask; + int armourStatusShowEnchantsMask = 512; + code |= armourStatusShowEnchantsMask; + code |= 0; + code |= 0; + code |= 0; + code |= 0; + code |= 0; + code |= 0; + code |= 0; + int notificationHungerMask = 131072; + code |= notificationHungerMask; + code |= 0; + code |= 0; + code |= 0; + int deathpointsMask = 2097152; + code |= deathpointsMask; + int notificationAirMask = 4194304; + code |= notificationAirMask; + int entityInfoMask = 8388608; + code |= entityInfoMask; return code; } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/player/CustomPlayer.java b/src/main/java/eu/univento/core/api/player/CustomPlayer.java index a85bc20..0e465e1 100644 --- a/src/main/java/eu/univento/core/api/player/CustomPlayer.java +++ b/src/main/java/eu/univento/core/api/player/CustomPlayer.java @@ -7,19 +7,22 @@ import com.mongodb.CursorType; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import eu.univento.core.Core; -import eu.univento.core.antihack.Hack; -import eu.univento.core.api.Actionbar; +import eu.univento.core.api.Hologram; import eu.univento.core.api.Utils; import eu.univento.core.api.database.MongoDB; +import eu.univento.core.api.effects.Blackscreen; import eu.univento.core.api.effects.Effects; import eu.univento.core.api.languages.Language; import eu.univento.core.api.languages.Messages; import eu.univento.core.api.server.ServerSettings; import eu.univento.core.api.server.Servers; +import eu.univento.core.api.shop.ShopItem; import eu.univento.core.api.utils.GameProfileBuilder; import eu.univento.core.api.utils.UUIDFetcher; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; import net.minecraft.server.v1_10_R1.*; import net.minecraft.server.v1_10_R1.World; import org.bson.Document; @@ -27,6 +30,10 @@ import org.bukkit.*; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.attribute.AttributeModifier; +import org.bukkit.boss.BarColor; +import org.bukkit.boss.BarFlag; +import org.bukkit.boss.BarStyle; +import org.bukkit.boss.BossBar; import org.bukkit.craftbukkit.v1_10_R1.CraftServer; import org.bukkit.craftbukkit.v1_10_R1.CraftWorld; import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; @@ -41,32 +48,34 @@ import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.util.*; import java.util.logging.Level; +import java.util.stream.Collectors; public class CustomPlayer extends CraftPlayer { - private static final HashMap PLAYERS = new HashMap<>(); + private static final HashMap PLAYERS = new HashMap<>(); private final Player PLAYER; private String customPrefix; private String customSuffix; private String customColor; - private String nickname; private boolean openInventory; - private MongoCollection playerCollection; - private MongoCollection friendCollection; - private MongoCollection onlinePlayerCollection; + private final MongoCollection playerCollection; + private final MongoCollection friendCollection; + private final MongoCollection onlinePlayerCollection; + private final MongoCollection warnCollection; private CustomPlayer(Player player) { super((CraftServer) Bukkit.getServer(), ((CraftPlayer) player).getHandle()); - PLAYERS.put(player.getName().toLowerCase(), this); + PLAYERS.put(player.getUniqueId(), this); PLAYER = player; - MongoDB mongoDB = Core.getMongoDB(); + MongoDB mongoDB = Core.getDatabaseManager().getMongoDB(); playerCollection = mongoDB.getDatabase().getCollection("players"); friendCollection = mongoDB.getDatabase().getCollection("friends"); onlinePlayerCollection = mongoDB.getDatabase().getCollection("online-players"); + warnCollection = mongoDB.getDatabase().getCollection("warns"); } @@ -83,13 +92,23 @@ public class CustomPlayer extends CraftPlayer { if (ServerSettings.isLobby()) setInDatabase("Pos", new BasicDBObject(location)); - if (PLAYERS.containsKey(getName().toLowerCase())) PLAYERS.remove(getName().toLowerCase()); + if (PLAYERS.containsKey(getUniqueId())) PLAYERS.remove(getUniqueId()); } public static CustomPlayer getPlayer(String player) { - if (PLAYERS.containsKey(player.toLowerCase())) { - return PLAYERS.get(player.toLowerCase()); + Player p = Bukkit.getPlayer(player); + if (PLAYERS.containsKey(p.getUniqueId())) { + return PLAYERS.get(p.getUniqueId()); } else { + return new CustomPlayer(p); + } + } + + public static CustomPlayer getPlayer(UUID player) { + if(PLAYERS.containsKey(player)) { + return PLAYERS.get(player); + } + else { Player p = Bukkit.getPlayer(player); return p == null ? null : new CustomPlayer(p); } @@ -97,42 +116,20 @@ public class CustomPlayer extends CraftPlayer { public static CustomPlayer getPlayer(Player player) { - return getPlayer(player.getName()); + return getPlayer(player.getUniqueId()); } - public static CustomPlayer getPlayer(UUID uuid) { - return getPlayer(UUIDFetcher.getName(uuid)); - } - - public Player getPLAYER() { return PLAYER; } - public void insertToDatabase() { - Document doc = new Document("uuid", getUniqueId().toString()); - - HashMap location = new HashMap<>(); - location.put("X", getLocation().getX()); - location.put("Y", getLocation().getY()); - location.put("Z", getLocation().getZ()); - location.put("Yaw", getLocation().getYaw()); - location.put("Pitch", getLocation().getPitch()); - - doc.put("Pos", new BasicDBObject(location)); - playerCollection.insertOne(doc); - } - - @Override public boolean hasPlayedBefore() { FindIterable cursor = playerCollection.find(new Document("uuid", getUniqueId().toString())); cursor.cursorType(CursorType.NonTailable); Document obj = cursor.first(); - if (obj == null) - return false; - return true; + return obj != null; } public void setRank(Rank rank) { @@ -143,11 +140,11 @@ public class CustomPlayer extends CraftPlayer { setInDatabase("tsid", id); } - public void setCoins(int coins) { + private void setCoins(int coins) { setInDatabase("coins", coins); } - public void setExperience(int experience) { + private void setExperience(int experience) { setInDatabase("experience", experience); } @@ -181,6 +178,25 @@ public class CustomPlayer extends CraftPlayer { setSettings(list); } + public void buy(ShopItem item) { + Map map = getBoughtItems(); + map.put(item, false); + setBoughtItems(map); + } + + public Map getBoughtItems() { + Map map = new HashMap<>(); + for (Map.Entry entry : getMapFromDatabase("bought").entrySet()) + map.put(ShopItem.valueOf(String.valueOf(entry.getKey())), Boolean.valueOf(String.valueOf(entry.getValue()))); + return map; + } + + private void setBoughtItems(Map map) { + Map items = new HashMap<>(); + for (Map.Entry entry : map.entrySet()) items.put(String.valueOf(entry.getKey()), entry.getValue()); + setInDatabase("bought", items); + } + public Rank getRank() { return Rank.valueOf(getStringFromDatabase("rank")); } @@ -221,7 +237,7 @@ public class CustomPlayer extends CraftPlayer { return getFoundSecrets().size(); } - public ArrayList getFoundSecrets() { + private ArrayList getFoundSecrets() { return getArrayListFromDatabase("foundSecrets"); } @@ -346,33 +362,35 @@ public class CustomPlayer extends CraftPlayer { return getRank().getValue() >= rank.getValue(); } - - public ArrayList getFriends() { + public Collection getFriends() { FindIterable cursor = friendCollection.find(new Document("uuid", getUniqueId().toString())); cursor.cursorType(CursorType.NonTailable); Document doc = cursor.first(); if (doc == null) return null; - return (ArrayList) doc.get("friends"); - } + LinkedList list = (LinkedList) doc.get("friends"); - private void setFriends(ArrayList friends) { - friendCollection.updateOne(new Document("uuid", getUniqueId().toString()), new Document("$set", new Document("friends", friends))); + return list.stream().map(FriendObject::new).collect(Collectors.toCollection(LinkedList::new)); } public boolean isFriend(UUID uuid) { return getFriends().contains(uuid); } - public void addFriend(UUID uuid) { - ArrayList list = getFriends(); - list.add(uuid); - setFriends(list); + + public boolean isMuted() { + return (boolean) getObjectFromDatbase("mute"); } - public void warn(Hack hack) { - //TODO: add actual function + public void warn(WarnReason reason, CustomPlayer warner, String proof) { + Document doc = new Document("uuid", getUniqueId().toString()); + doc.put("reason", reason.name()); + doc.put("warner", warner.getUniqueId().toString()); + doc.put("date", new Date()); + doc.put("proof", proof); + + warnCollection.insertOne(doc); } public String getPrefix() { @@ -435,9 +453,74 @@ public class CustomPlayer extends CraftPlayer { setCoins(getCoins() - coins); } + /* + @Deprecated + public void sendActionBar(String text) { + IChatBaseComponent cbc = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + text + "\"}"); + PacketPlayOutChat ppoc = new PacketPlayOutChat(cbc, (byte) 2); + sendPacket(ppoc); + } + */ public void sendActionBar(String text) { - Actionbar.send(PLAYER, text); + spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(text)); + } + + public void sendTitle(int fadeIn, int stay, int fadeOut, String title, String subtitle) { + PacketPlayOutTitle packetPlayOutTimes = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TIMES, null, fadeIn, stay, fadeOut); + sendPacket(packetPlayOutTimes); + + if (subtitle != null) { + subtitle = ChatColor.translateAlternateColorCodes('&', subtitle); + IChatBaseComponent titleSub = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + subtitle + "\"}"); + PacketPlayOutTitle packetPlayOutSubTitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.SUBTITLE, titleSub); + sendPacket(packetPlayOutSubTitle); + } + + if (title != null) { + title = ChatColor.translateAlternateColorCodes('&', title); + IChatBaseComponent titleMain = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + title + "\"}"); + PacketPlayOutTitle packetPlayOutTitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TITLE, titleMain); + sendPacket(packetPlayOutTitle); + } + } + + public BossBar sendBossBar(String text, BarColor color, BarStyle style, BarFlag flag) { + BossBar bar = Bukkit.createBossBar(text, color, style, flag); + bar.addPlayer(PLAYER); + return bar; + } + + public Hologram sendHologram(Location location, String... text) { + Hologram hologram = new Hologram(text, location); + hologram.showPlayer(this); + return hologram; + } + + public void sendTabHeaderAndFooter(String header, String footer) { + if (header == null) + header = ""; + header = ChatColor.translateAlternateColorCodes('&', header); + + if (footer == null) + footer = ""; + footer = ChatColor.translateAlternateColorCodes('&', footer); + + header = header.replaceAll("%player%", getDisplayName()); + footer = footer.replaceAll("%player%", getDisplayName()); + + IChatBaseComponent tabTitle = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + header + "\"}"); + IChatBaseComponent tabFoot = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + footer + "\"}"); + PacketPlayOutPlayerListHeaderFooter headerPacket = new PacketPlayOutPlayerListHeaderFooter(tabTitle); + try { + Field field = headerPacket.getClass().getDeclaredField("b"); + field.setAccessible(true); + field.set(headerPacket, tabFoot); + } catch (Exception e) { + e.printStackTrace(); + } finally { + sendPacket(headerPacket); + } } public void addExperience(int experience) { @@ -459,6 +542,7 @@ public class CustomPlayer extends CraftPlayer { giveExp(getExperience()); } + @Deprecated public void playParticle(Location loc, EnumParticle ep, float f, int count) { if (hasEffects()) Effects.playEffectToPlayer(PLAYER, loc, ep, f, count); } @@ -468,7 +552,7 @@ public class CustomPlayer extends CraftPlayer { getAttribute(Attribute.GENERIC_ATTACK_SPEED).addModifier(modifier); } - public double getAttackSpeed() { + private double getAttackSpeed() { return getAttribute(Attribute.GENERIC_ATTACK_SPEED).getValue(); } @@ -479,6 +563,7 @@ public class CustomPlayer extends CraftPlayer { instance.setBaseValue(16.0D); } + @Deprecated public Messages getMessages() { return new Messages(this); } @@ -495,6 +580,7 @@ public class CustomPlayer extends CraftPlayer { setSetting("nicked", nicked); } + @Deprecated private void loadSkin(String name) { //Skin skin = new Skin(UUIDFetcher.getUUID(name).toString()); GameProfile skin; @@ -525,15 +611,12 @@ public class CustomPlayer extends CraftPlayer { } } + @Deprecated public void removeNick() { setNick(getName()); } - public String getNick() { - if (nickname != null) return nickname; - return null; - } - + @Deprecated public void setNick(String name) { setDisplayName(name); Field nameField = getField(GameProfile.class, "name"); @@ -561,13 +644,17 @@ public class CustomPlayer extends CraftPlayer { } public void strikeLightning(Location loc) { - World nmsWorld = ((CraftWorld)loc.getWorld()).getHandle(); + World nmsWorld = ((CraftWorld) loc.getWorld()).getHandle(); EntityLightning lightning = new EntityLightning(nmsWorld, loc.getX(), loc.getY(), loc.getZ(), true); sendPacket(new PacketPlayOutSpawnEntityWeather(lightning)); playSound(loc, Sound.ENTITY_LIGHTNING_IMPACT, 20.0F, 1.0F); playSound(loc, Sound.ENTITY_LIGHTNING_THUNDER, 20.0F, 1.0F); } + public void setBlackScreen(int seconds) { + Blackscreen.setBlack(PLAYER, seconds); + } + @Override public boolean isOnline() { FindIterable cursor = onlinePlayerCollection.find(new Document("uuid", getUniqueId().toString())); @@ -576,6 +663,10 @@ public class CustomPlayer extends CraftPlayer { return doc != null; } + public void setStoryResourcePack() { + setResourcePack("http://univento.eu/storyPack.zip"); + } + private void setInDatabase(String name, Object obj) { playerCollection.updateOne(new Document("uuid", getUniqueId().toString()), new Document("$set", new Document(name, obj))); } @@ -632,7 +723,7 @@ public class CustomPlayer extends CraftPlayer { Scoreboard board = getScoreboard(); board.getTeams().forEach(Team::unregister); - for(Rank rank : Rank.values()) { + for (Rank rank : Rank.values()) { Team team = board.registerNewTeam(rank.getTeam()); team.setPrefix(rank.getTab()); team.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.ALWAYS); @@ -680,6 +771,7 @@ public class CustomPlayer extends CraftPlayer { return null; } + @Deprecated public void refreshTablist() { for (CustomPlayer player : Core.getOnlinePlayers()) { setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); @@ -687,8 +779,22 @@ public class CustomPlayer extends CraftPlayer { } } - public Player.Spigot spigot() { - return PLAYER.spigot(); + /** + * + * @param location location for effect + * @param effect particle effect + * @param id + * @param data + * @param offsetX offset in x direction + * @param offsetY offset in y direction + * @param offsetZ offset in z direction + * @param speed particle speed + * @param particleCount count of showed particles + * @param radius effect radius + */ + public void playEffect(Location location, Effect effect, int id, int data, float offsetX, float offsetY, float offsetZ, float speed, int particleCount, int radius) { + if(hasEffects()) + spigot().playEffect(location, effect, id, data, offsetX, offsetY, offsetZ, speed, particleCount, radius); } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/player/FriendObject.java b/src/main/java/eu/univento/core/api/player/FriendObject.java new file mode 100644 index 0000000..5c82171 --- /dev/null +++ b/src/main/java/eu/univento/core/api/player/FriendObject.java @@ -0,0 +1,27 @@ +package eu.univento.core.api.player; + +import eu.univento.core.api.utils.UUIDFetcher; + +import java.util.UUID; + +/** + * @author joethei + * @version 0.1 + * Created at 21:15 on 25.07.2016. + */ +public class FriendObject { + + private UUID uuid; + + public FriendObject(UUID uuid) { + this.uuid = uuid; + } + + public UUID getUuid() { + return uuid; + } + + public String getName() { + return UUIDFetcher.getName(uuid); + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/player/LabyMod.java b/src/main/java/eu/univento/core/api/player/LabyMod.java index db12616..5194fc7 100644 --- a/src/main/java/eu/univento/core/api/player/LabyMod.java +++ b/src/main/java/eu/univento/core/api/player/LabyMod.java @@ -13,7 +13,19 @@ public enum LabyMod { DAMAGEINDICATOR("DAMAGEINDICATOR", 9), MINIMAP_RADAR("MINIMAP_RADAR", 10); - LabyMod(String s, int n) { + private String name; + private int value; + LabyMod(String name, int value) { + this.name = name; + this.value = value; + } + + public String getName() { + return name; + } + + public int getValue() { + return value; } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/player/Rank.java b/src/main/java/eu/univento/core/api/player/Rank.java index 399a733..8da50fb 100644 --- a/src/main/java/eu/univento/core/api/player/Rank.java +++ b/src/main/java/eu/univento/core/api/player/Rank.java @@ -1,22 +1,22 @@ package eu.univento.core.api.player; public enum Rank { - Admin(16, "§4", "§8[§4Admin§8] ", "§8» ", "a", "§4Admin | "), - SrDeveloper(15, "§3", "§8[§3SrDev§8] ", "§8» ", "c", "§3SrDev | "), - SrBuilder(14, "§2", "§8[§2SrBuilder§8] ", "§8» ", "f", "§2SrBuilder | "), - SrSupporter(13, "§9", "§8[§9SrSupr§8] ", "§8» ", "i", "§9SrSup | "), - Developer(12, "§3", "§8[§3Dev§8] ", "§8» ", "d", "§3Dev | "), - Builder(11, "§2", "§8[§3Builder§8] ", "§8» ", "g", "§2Builder | "), - Supporter(10, "§9", "§8[§9Sup§8] ", "§8» ", "j", "§9Sup | "), - JrDeveloper(9, "§3", "§8[§3JrDev§8] ", "§8» ", "e", "§3JrDev | "), - JrBuilder(8, "§2", "§8[§2JrBuilder§8] ", "§8» ", "h", "§2JrBuilder | "), - JrSupporter(7, "§9", "§8[§9JrSup§8] ", "§8» ", "k", "§9JrSup | "), - Manager(6, "§c", "§8[§cManager§8] ", "§8» ", "b", "§cManager | "), - Grafik(5, "§e", "§8[§eGrafiker§8] ", "§8» ", "l", "§eGrafik | "), - Sound(4, "§e", "§8[§eSound§8] ", "§8» ", "m", "§eSound | "), - Partner(3, "§5", "§5", "§8» ", "n", "§5"), - Premium(2, "§6", "§6", "§8» ", "o", "§6"), - Player(1, "§7", "§7", "§8» ", "p", "§7"); + Admin(16, "§4", "§8[§4Admin§8] ", " §8Ȥ7 ", "a", "§4Admin | "), + SrDeveloper(15, "§3", "§8[§3SrDev§8] ", " §8Ȥ7 ", "c", "§3SrDev | "), + SrBuilder(14, "§2", "§8[§2SrBuilder§8] ", " §8Ȥ7 ", "f", "§2SrBuilder | "), + SrSupporter(13, "§9", "§8[§9SrSupr§8] ", " §8Ȥ7 ", "i", "§9SrSup | "), + Developer(12, "§3", "§8[§3Dev§8] ", " §8Ȥ7 ", "d", "§3Dev | "), + Builder(11, "§2", "§8[§2Builder§8] ", " §8Ȥ7 ", "g", "§2Builder | "), + Supporter(10, "§9", "§8[§9Sup§8] ", " §8Ȥ7 ", "j", "§9Sup | "), + JrDeveloper(9, "§3", "§8[§3JrDev§8] ", " §8Ȥ7 ", "e", "§3JrDev | "), + JrBuilder(8, "§2", "§8[§2JrBuilder§8] ", " §8Ȥ7 ", "h", "§2JrBuilder | "), + JrSupporter(7, "§9", "§8[§9JrSup§8] ", " §8Ȥ7 ", "k", "§9JrSup | "), + Manager(6, "§c", "§8[§cManager§8] ", " §8Ȥ7 ", "b", "§cManager | "), + Grafik(5, "§e", "§8[§eGrafiker§8] ", " §8Ȥ7 ", "l", "§eGrafik | "), + Sound(4, "§e", "§8[§eSound§8] ", " §8Ȥ7 ", "m", "§eSound | "), + Partner(3, "§5", "§5", " §8Ȥ7 ", "n", "§5"), + Premium(2, "§6", "§6", " §8§7» ", "o", "§6"), + Player(1, "§7", "§7", " §8Ȥ7 ", "p", "§7"); private final int value; private final String color; diff --git a/src/main/java/eu/univento/core/api/player/Skin.java b/src/main/java/eu/univento/core/api/player/Skin.java index 24d7f2f..eaae34b 100644 --- a/src/main/java/eu/univento/core/api/player/Skin.java +++ b/src/main/java/eu/univento/core/api/player/Skin.java @@ -11,7 +11,7 @@ import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; class Skin { - private String uuid; + private final String uuid; private String name; private String value; private String signature; diff --git a/src/main/java/eu/univento/core/api/player/SpectateManager.java b/src/main/java/eu/univento/core/api/player/SpectateManager.java new file mode 100644 index 0000000..57e831e --- /dev/null +++ b/src/main/java/eu/univento/core/api/player/SpectateManager.java @@ -0,0 +1,34 @@ +package eu.univento.core.api.player; + +import java.util.LinkedList; +import java.util.List; + +/** + * @author joethei + * @version 0.1 + * Created at 16:18 on 17.07.2016. + */ +public class SpectateManager { + + private static final List spectators = new LinkedList<>(); + + public static Spectator get(CustomPlayer p) { + for(Spectator spectator : spectators) { + if(spectator.getPlayer().equals(p)) return spectator; + } + return null; + } + + public static void add(Spectator spectator) { + if(!spectators.contains(spectator)) spectators.add(spectator); + } + + public static void remove(Spectator spectator) { + if(spectators.contains(spectator)) spectators.remove(spectator); + } + + public static boolean contains(CustomPlayer p) { + return get(p) != null; + } + +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/player/Spectator.java b/src/main/java/eu/univento/core/api/player/Spectator.java index 6c768d0..1b4ec53 100644 --- a/src/main/java/eu/univento/core/api/player/Spectator.java +++ b/src/main/java/eu/univento/core/api/player/Spectator.java @@ -1,67 +1,60 @@ package eu.univento.core.api.player; import eu.univento.core.Core; +import eu.univento.core.api.game.PlayerManager; +import eu.univento.core.api.items.ItemBuilder; +import eu.univento.core.api.items.ScrollingInventory; import eu.univento.core.api.server.ServerSettings; import org.bukkit.GameMode; -import org.bukkit.entity.Player; - -import java.util.ArrayList; +import org.bukkit.Material; /** - * * @author joethei - * @version 1.0 + * @version 2.0 */ public class Spectator { - /** - * contains all spectators - */ - private static ArrayList spectators = new ArrayList<>(); + private final CustomPlayer player; - /** - * adds player to spectators - * @param p CustomPlayer - */ - public static void add(CustomPlayer p) { - for (Player on : Core.getOnlinePlayers()) { - on.hidePlayer(p); + public Spectator(CustomPlayer player) { + this.player = player; + for (CustomPlayer players : Core.getOnlinePlayers()) + players.hidePlayer(player); + SpectateManager.add(this); + player.setGameMode(GameMode.ADVENTURE); + player.setAllowFlight(true); + player.setFlying(true); + } + + public CustomPlayer getPlayer() { + return player; + } + + public void remove() { + for(CustomPlayer players : Core.getOnlinePlayers()) + players.hidePlayer(player); + player.setGameMode(ServerSettings.getGameMode()); + player.setAllowFlight(false); + player.setFlying(false); + SpectateManager.remove(this); + if(player.getSpectatorTarget() != null) player.setSpectatorTarget(null); + } + + public void spectate(CustomPlayer p) throws NullPointerException { + if(!SpectateManager.contains(p)) throw new NullPointerException("The player " + player.getName() + " is not an spectator"); + if(!p.isOnline()) throw new NullPointerException("The player " + p.getName() + " is not online"); + player.setSpectatorTarget(p); + } + + public void resetSpectateTarget() { + if(player.getSpectatorTarget() != null) player.setSpectatorTarget(null); + } + + public void openPlayerListInventory() { + ScrollingInventory inventory = new ScrollingInventory(player, player.getMessage("Game.Menu.SpectatorMenu")); + for(CustomPlayer players : PlayerManager.getPlayers()) { + inventory.addItem(new ItemBuilder(Material.SKULL_ITEM).durability((short) 3).skullOwner(players.getDisplayName()).name(players.getDisplayName()).make()); } - spectators.add(p); - p.setGameMode(GameMode.ADVENTURE); - p.setAllowFlight(true); - p.setFlying(true); + inventory.openInventory(); } - - /** - * removes player from spectator - * @param p CustomPlayer - */ - public static void remove(CustomPlayer p) { - for (Player on : Core.getOnlinePlayers()) { - on.showPlayer(p); - } - spectators.remove(p); - p.setGameMode(ServerSettings.getGameMode()); - p.setAllowFlight(false); - p.setFlying(false); - } - - /** - * gets all spectators - * @return ArrayList - */ - public static ArrayList getSpectators() { - return spectators; - } - - /** - * checks if players is spectator - * @param p CustomPlayer - * @return true/false - */ - public static boolean is(CustomPlayer p) { - return spectators.contains(p); - } - } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/player/WarnReason.java b/src/main/java/eu/univento/core/api/player/WarnReason.java new file mode 100644 index 0000000..a704e45 --- /dev/null +++ b/src/main/java/eu/univento/core/api/player/WarnReason.java @@ -0,0 +1,27 @@ +package eu.univento.core.api.player; + +/** + * @author joethei + * @version 0.1 + * Created at 21:06 on 13.07.2016. + */ +public enum WarnReason { + ADVERTISEMENT("Advertisement", 10), + SPAM("Spamming", 10); + + private String name; + private int value; + + WarnReason(String name, int value) { + this.name = name; + this.value = value; + } + + public String getName() { + return name; + } + + public int getValue() { + return value; + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/server/Game.java b/src/main/java/eu/univento/core/api/server/Game.java deleted file mode 100644 index bd4ca7d..0000000 --- a/src/main/java/eu/univento/core/api/server/Game.java +++ /dev/null @@ -1,19 +0,0 @@ -package eu.univento.core.api.server; - -/** - * all minigames with description - * @author joethei - * @version 1.0 - */ -public enum Game { - - //TODO: lookout for some TODOs in this file - WoolGet, - FlagAttack, - Free4All, - TrashGames, - HulkFight, - Maya, - FallingAttack, - Worms -} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/server/GameInfo.java b/src/main/java/eu/univento/core/api/server/GameInfo.java index bb55932..3ab2bcc 100644 --- a/src/main/java/eu/univento/core/api/server/GameInfo.java +++ b/src/main/java/eu/univento/core/api/server/GameInfo.java @@ -4,12 +4,16 @@ package eu.univento.core.api.server; * @author joethei * @version 0.1 */ -public class GameInfo { +class GameInfo { - Game game; + private final ServerType serverType; - public GameInfo(Game game) { - this.game = game; + public GameInfo(ServerType serverType) { + this.serverType = serverType; + } + + public ServerType getServerType() { + return serverType; } public int getPlayerCount() { diff --git a/src/main/java/eu/univento/core/api/server/MojangService.java b/src/main/java/eu/univento/core/api/server/MojangService.java index 2207006..0de0bae 100644 --- a/src/main/java/eu/univento/core/api/server/MojangService.java +++ b/src/main/java/eu/univento/core/api/server/MojangService.java @@ -29,8 +29,9 @@ public enum MojangService { * [url]http://minecraft.gamepedia.com/User_talk:Oxguy3/Minecraft.net_API[/url] */ - private String name, serviceURL; - private JSONParser jsonParser = new JSONParser(); + private final String name; + private final String serviceURL; + private final JSONParser jsonParser = new JSONParser(); MojangService(String name, String serviceURL) { this.name = name; @@ -41,22 +42,12 @@ public enum MojangService { return name; } - /** - * Check the current Mojang service for it's status, errors are ignored. - * - * @return Status of the service. - */ - public Status getStatus() { - return getStatus(true); - } - /** * Check the current Mojang service for it's status. * - * @param suppressErrors - Don't print errors in console. * @return Status of the service. */ - public Status getStatus(boolean suppressErrors) { + private Status getStatus() { try { URL url = new URL("[url]http://status.mojang.com/check?service=[/url]" + serviceURL); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); @@ -70,7 +61,7 @@ public enum MojangService { } catch (IOException | ParseException exception) { - if (!suppressErrors) { + if (!true) { exception.printStackTrace(); } @@ -84,7 +75,9 @@ public enum MojangService { OFFLINE("Offline", ChatColor.DARK_RED.toString(), "Experiencing problems!"), UNKNOWN("Unknown", ChatColor.WHITE.toString(), "Couldn't connect to Mojang!"); - private String status, color, description; + private final String status; + private final String color; + private final String description; Status(String status, String color, String description) { this.status = status; diff --git a/src/main/java/eu/univento/core/api/server/NetworkData.java b/src/main/java/eu/univento/core/api/server/NetworkData.java index 81415b5..07db660 100644 --- a/src/main/java/eu/univento/core/api/server/NetworkData.java +++ b/src/main/java/eu/univento/core/api/server/NetworkData.java @@ -14,8 +14,6 @@ public class NetworkData implements PluginMessageListener{ private CustomPlayer player; private int totalPlayerCount; - private String serverName; - private int serverPlayerCount; public NetworkData(CustomPlayer player) { this.player = player; @@ -51,8 +49,8 @@ public class NetworkData implements PluginMessageListener{ this.totalPlayerCount = input.readInt(); return; } - this.serverName = server; - this.serverPlayerCount = input.readInt(); + String serverName = server; + int serverPlayerCount = input.readInt(); } } diff --git a/src/main/java/eu/univento/core/api/server/ServerDatabase.java b/src/main/java/eu/univento/core/api/server/ServerDatabase.java index a52dcd7..a315d43 100644 --- a/src/main/java/eu/univento/core/api/server/ServerDatabase.java +++ b/src/main/java/eu/univento/core/api/server/ServerDatabase.java @@ -3,7 +3,6 @@ package eu.univento.core.api.server; import eu.univento.core.Core; import eu.univento.core.api.database.MySQL; -import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -11,57 +10,45 @@ import java.sql.SQLException; * @author joethei * @version 0.1 */ -public class ServerDatabase { +class ServerDatabase { static String getIP(String name) { - MySQL sql = Core.getMySQL(); + MySQL sql = Core.getDatabaseManager().getMySQL(); try { - sql.openConnection(); - PreparedStatement st = sql.getConnection().prepareStatement("SELECT ip FROM Servers WHERE name='" + name + "'"); - ResultSet rs = st.executeQuery(); + ResultSet rs = sql.query("SELECT ip FROM Servers WHERE name='" + name + "';"); if(rs.next()) { - String ip = rs.getString("ip"); - sql.closeConnection(); - return ip; + return rs.getString("ip"); } return null; - } catch (SQLException | ClassNotFoundException e) { + } catch (SQLException e) { e.printStackTrace(); return null; } } static int getPort(String name) { - MySQL sql = Core.getMySQL(); + MySQL sql = Core.getDatabaseManager().getMySQL(); try { - sql.openConnection(); - PreparedStatement st = sql.getConnection().prepareStatement("SELECT port FROM Servers WHERE name='" + name + "'"); - ResultSet rs = st.executeQuery(); + ResultSet rs = sql.query("SELECT port FROM Servers WHERE name='" + name + "';"); if(rs.next()) { - int port = rs.getInt("port"); - sql.closeConnection(); - return port; + return rs.getInt("port"); } return 0; - } catch (SQLException | ClassNotFoundException e) { + } catch (SQLException e) { e.printStackTrace(); return 0; } } static String getMotd(String name) { - MySQL sql = Core.getMySQL(); + MySQL sql = Core.getDatabaseManager().getMySQL(); try { - sql.openConnection(); - PreparedStatement st = sql.getConnection().prepareStatement("SELECT motd FROM Servers WHERE name='" + name + "'"); - ResultSet rs = st.executeQuery(); + ResultSet rs = sql.query("SELECT motd FROM Servers WHERE name='" + name + "';"); if(rs.next()) { - String motd = rs.getString("motd"); - sql.closeConnection(); - return motd; + return rs.getString("motd"); } return null; - } catch (SQLException | ClassNotFoundException e) { + } catch (SQLException e) { e.printStackTrace(); return null; } diff --git a/src/main/java/eu/univento/core/api/server/ServerInfo.java b/src/main/java/eu/univento/core/api/server/ServerInfo.java index fc08428..a499b03 100644 --- a/src/main/java/eu/univento/core/api/server/ServerInfo.java +++ b/src/main/java/eu/univento/core/api/server/ServerInfo.java @@ -8,12 +8,12 @@ import java.util.regex.Pattern; */ public class ServerInfo { - String name; - ServerPinger pinger; + private final String name; + private final ServerPinger pinger; public ServerInfo(String name) { this.name = name; - pinger = new ServerPinger(name, 200); + pinger = new ServerPinger(name); pinger.ping(); } @@ -21,9 +21,9 @@ public class ServerInfo { return name; } - public Game getGame() { + public ServerType getGame() { String[] parts = getMotd().split(Pattern.quote(";")); - return Game.valueOf(parts[0]); + return ServerType.valueOf(parts[0]); } public String getGameState() { diff --git a/src/main/java/eu/univento/core/api/server/ServerPinger.java b/src/main/java/eu/univento/core/api/server/ServerPinger.java index 982b4a2..c8f5a70 100644 --- a/src/main/java/eu/univento/core/api/server/ServerPinger.java +++ b/src/main/java/eu/univento/core/api/server/ServerPinger.java @@ -6,7 +6,7 @@ import java.net.Socket; import java.net.SocketException; import java.nio.charset.Charset; -public class ServerPinger { +class ServerPinger { private String address; private int port; @@ -17,13 +17,13 @@ public class ServerPinger { private int maxplayers; private String motd; - public ServerPinger(String name, int timeout){ + public ServerPinger(String name){ this.address = ServerDatabase.getIP(name); this.port = ServerDatabase.getPort(name); - this.timeout = timeout; + this.timeout = 200; } - public String getAddress(){ + private String getAddress(){ return this.address; } @@ -31,7 +31,7 @@ public class ServerPinger { this.address = address; } - public int getPort(){ + private int getPort(){ return this.port; } @@ -39,7 +39,7 @@ public class ServerPinger { this.port = port; } - public int getTimeout(){ + private int getTimeout(){ return this.timeout; } @@ -156,8 +156,6 @@ public class ServerPinger { inputStreamReader.close(); inputStream.close(); socket.close(); - } catch (SocketException exception) { - this.setOnline(false); } catch (IOException exception) { this.setOnline(false); } diff --git a/src/main/java/eu/univento/core/api/server/ServerSettings.java b/src/main/java/eu/univento/core/api/server/ServerSettings.java index 9cf13d8..5958695 100644 --- a/src/main/java/eu/univento/core/api/server/ServerSettings.java +++ b/src/main/java/eu/univento/core/api/server/ServerSettings.java @@ -20,16 +20,16 @@ public class ServerSettings { private static boolean debug; private static boolean mute; private static boolean game; - private static Game playedGame; + private static ServerType serverType; private static GameMode gameMode; private static String gameState; - public static Game getPlayedGame() { - return playedGame; + public static ServerType getServerType() { + return serverType; } - public static void setPlayedGame(Game game) { - ServerSettings.playedGame = game; + public static void setServerType(ServerType serverType) { + ServerSettings.serverType = serverType; } public static GameMode getGameMode() { @@ -56,7 +56,7 @@ public class ServerSettings { ServerSettings.build = build; if(!build) { PluginManager pm = Bukkit.getPluginManager(); - new Build(Core.getInstance(), "build", "build", "b"); + new Build(Core.getInstance(), "build", "b"); pm.registerEvents(new Blocks(), Core.getInstance()); Core.log(Level.INFO, "Build Modus aktiviert"); } @@ -66,16 +66,16 @@ public class ServerSettings { return lobby; } - public static void setLobby(boolean lobby) { - ServerSettings.lobby = lobby; + public static void setLobby() { + ServerSettings.lobby = true; } public static boolean isDebug() { return debug; } - public static void setDebug(boolean debug) { - ServerSettings.debug = debug; + public static void setDebug() { + ServerSettings.debug = true; } public static boolean isMute() { diff --git a/src/main/java/eu/univento/core/api/server/ServerType.java b/src/main/java/eu/univento/core/api/server/ServerType.java new file mode 100644 index 0000000..32649c2 --- /dev/null +++ b/src/main/java/eu/univento/core/api/server/ServerType.java @@ -0,0 +1,29 @@ +package eu.univento.core.api.server; + +/** + * @author joethei + * @version 0.1 + * Created at 08:39 on 20.07.2016. + */ +public enum ServerType { + + LOBBY("Lobby", "§6Lobby"), + GAME_FREE4ALL("Free4All", "§6Free4All"), + GAME_TRASHGAMES("TrashGames", "§6TrashGames"); + + private String name; + private String prefix; + + ServerType(String name, String prefix) { + this.name = name; + this.prefix = prefix; + } + + public String getName() { + return name; + } + + public String getPrefix() { + return prefix; + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/shop/PayType.java b/src/main/java/eu/univento/core/api/shop/PayType.java new file mode 100644 index 0000000..f7f083e --- /dev/null +++ b/src/main/java/eu/univento/core/api/shop/PayType.java @@ -0,0 +1,22 @@ +package eu.univento.core.api.shop; + +/** + * @author joethei + * @version 0.1 + * Created at 17:10 on 19.07.2016. + */ +public enum PayType { + //TODO: change to real pay type names. + COINS("Coins"), + EXP("Experience"); + + private String name; + + PayType(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/shop/ShopCategory.java b/src/main/java/eu/univento/core/api/shop/ShopCategory.java new file mode 100644 index 0000000..ac214c1 --- /dev/null +++ b/src/main/java/eu/univento/core/api/shop/ShopCategory.java @@ -0,0 +1,29 @@ +package eu.univento.core.api.shop; + +import eu.univento.core.api.server.ServerType; + +/** + * @author joethei + * @version 0.1 + * Created at 08:36 on 20.07.2016. + */ +enum ShopCategory { + + LOBBY("Lobby", ServerType.LOBBY); + + private String name; + private ServerType type; + + ShopCategory(String name, ServerType type) { + this.name = name; + this.type = type; + } + + public String getName() { + return name; + } + + public ServerType getType() { + return type; + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/shop/ShopItem.java b/src/main/java/eu/univento/core/api/shop/ShopItem.java new file mode 100644 index 0000000..4f04e5d --- /dev/null +++ b/src/main/java/eu/univento/core/api/shop/ShopItem.java @@ -0,0 +1,48 @@ +package eu.univento.core.api.shop; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +/** + * @author joethei + * @version 0.1 + * Created at 17:09 on 19.07.2016. + */ +public enum ShopItem { + + TestItem("Test Item", ShopCategory.LOBBY, new ItemStack(Material.STONE), 20, PayType.COINS); + + private String name; + private ShopCategory category; + private ItemStack item; + private int price; + private PayType payType; + + ShopItem(String name, ShopCategory category, ItemStack item, int price, PayType payType) { + this.name = name; + this.category = category; + this.item = item; + this.price = price; + this.payType = payType; + } + + public String getName() { + return name; + } + + public ShopCategory getCategory() { + return category; + } + + public ItemStack getItem() { + return item; + } + + public int getPrice() { + return price; + } + + public PayType getPayType() { + return payType; + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/shop/ShopMenu.java b/src/main/java/eu/univento/core/api/shop/ShopMenu.java new file mode 100644 index 0000000..52965bd --- /dev/null +++ b/src/main/java/eu/univento/core/api/shop/ShopMenu.java @@ -0,0 +1,48 @@ +package eu.univento.core.api.shop; + + +import eu.univento.core.api.player.CustomPlayer; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.plugin.Plugin; + +import java.util.Collections; +import java.util.List; + +/** + * @author joethei + * @version 0.1 + * Created at 21:53 on 19.07.2016. + */ +public class ShopMenu implements Listener{ + + private String name; + private List items; + + + public ShopMenu(Plugin plugin, String name, ShopItem... items) { + this.name = name; + Collections.addAll(this.items, items); + Bukkit.getPluginManager().registerEvents(this, plugin); + } + + public Inventory getInventory() { + Inventory inv = Bukkit.createInventory(null, 18, name); + + for(ShopItem item : items) + inv.addItem(item.getItem()); + + return inv; + } + + @EventHandler + public void onInventoryClick(InventoryClickEvent e) { + CustomPlayer p = CustomPlayer.getPlayer((Player) e.getWhoClicked()); + items.stream().filter(shopItem -> shopItem.getItem().equals(e.getCurrentItem())).forEach(p::buy); + } + +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/shop/entity/ShopEntity.java b/src/main/java/eu/univento/core/api/shop/entity/ShopEntity.java new file mode 100644 index 0000000..4ff3e2e --- /dev/null +++ b/src/main/java/eu/univento/core/api/shop/entity/ShopEntity.java @@ -0,0 +1,84 @@ +package eu.univento.core.api.shop.entity; + +import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.shop.ShopMenu; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.plugin.Plugin; + +/** + * @author joethei + * @version 0.1 + * Created at 10:03 on 20.07.2016. + */ +class ShopEntity implements Listener{ + + private LivingEntity entity; + + private EntityType type; + private String name; + private Location location; + private ShopMenu menu; + + ShopEntity(Plugin plugin, EntityType type, String name, Location location, ShopMenu menu) { + this.type = type; + this.name = name; + this.location = location; + this.menu = menu; + Bukkit.getPluginManager().registerEvents(this, plugin); + spawn(); + } + + public void spawn() { + if(entity == null) { + LivingEntity entity = (LivingEntity) location.getWorld().spawnEntity(location, type); + entity.setCustomName(name); + entity.setCustomNameVisible(true); + entity.setAI(false); + + this.entity = entity; + } + } + + public void despawn() { + if(entity != null) { + entity.remove(); + } + } + + public EntityType getType() { + return type; + } + + public String getName() { + return name; + } + + public Location getLocation() { + return location; + } + + public ShopMenu getMenu() { + return menu; + } + + public LivingEntity getEntity() { + return entity; + } + + @EventHandler + public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + Entity entity = e.getRightClicked(); + if(entity.getType() == type && name.equals(entity.getCustomName())) { + e.setCancelled(true); + p.openInventory(menu.getInventory()); + } + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/shop/entity/ShopIronGolem.java b/src/main/java/eu/univento/core/api/shop/entity/ShopIronGolem.java new file mode 100644 index 0000000..5d14858 --- /dev/null +++ b/src/main/java/eu/univento/core/api/shop/entity/ShopIronGolem.java @@ -0,0 +1,18 @@ +package eu.univento.core.api.shop.entity; + +import eu.univento.core.api.shop.ShopMenu; +import org.bukkit.Location; +import org.bukkit.entity.EntityType; +import org.bukkit.plugin.Plugin; + +/** + * @author joethei + * @version 0.1 + * Created at 11:15 on 20.07.2016. + */ +public class ShopIronGolem extends ShopEntity{ + + public ShopIronGolem(Plugin plugin, EntityType type, String name, Location location, ShopMenu menu) { + super(plugin, type, name, location, menu); + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/shop/entity/ShopVillager.java b/src/main/java/eu/univento/core/api/shop/entity/ShopVillager.java new file mode 100644 index 0000000..73dfe22 --- /dev/null +++ b/src/main/java/eu/univento/core/api/shop/entity/ShopVillager.java @@ -0,0 +1,23 @@ +package eu.univento.core.api.shop.entity; + +import eu.univento.core.api.shop.ShopMenu; +import org.bukkit.Location; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Villager; +import org.bukkit.plugin.Plugin; + +/** + * @author joethei + * @version 0.1 + * Created at 17:56 on 19.07.2016. + */ +public class ShopVillager extends ShopEntity { + + public ShopVillager(Plugin plugin, String name, Location location, Villager.Profession profession, ShopMenu menu) { + super(plugin, EntityType.VILLAGER, name, location, menu); + Villager villager = (Villager) getEntity(); + villager.setProfession(profession); + villager.setAdult(); + } + +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/utils/Camera.java b/src/main/java/eu/univento/core/api/utils/Camera.java index addd73e..6dc3a8b 100644 --- a/src/main/java/eu/univento/core/api/utils/Camera.java +++ b/src/main/java/eu/univento/core/api/utils/Camera.java @@ -8,11 +8,10 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; -public class Camera { +class Camera { //TODO: add full functionality - private String name; private int time; private ArrayList players = new ArrayList<>(); private ArrayList locations = new ArrayList<>(); @@ -92,7 +91,6 @@ public class Camera { } public Camera(String name) { - this.name = name; load(); } diff --git a/src/main/java/eu/univento/core/api/utils/Direction.java b/src/main/java/eu/univento/core/api/utils/Direction.java index 3184740..4bf2b1b 100644 --- a/src/main/java/eu/univento/core/api/utils/Direction.java +++ b/src/main/java/eu/univento/core/api/utils/Direction.java @@ -11,10 +11,10 @@ public enum Direction NORTHWEST(1, -1), SOUTHWEST(-1, -1); - private int x; - private int z; + private final int x; + private final int z; - private Direction(int x, int z) { this.x = x; + Direction(int x, int z) { this.x = x; this.z = z; } public int getX() diff --git a/src/main/java/eu/univento/core/api/utils/GameProfileBuilder.java b/src/main/java/eu/univento/core/api/utils/GameProfileBuilder.java index 006ddbd..b354770 100644 --- a/src/main/java/eu/univento/core/api/utils/GameProfileBuilder.java +++ b/src/main/java/eu/univento/core/api/utils/GameProfileBuilder.java @@ -28,9 +28,9 @@ public class GameProfileBuilder { private static final String JSON_SKIN = "{\"timestamp\":%d,\"profileId\":\"%s\",\"profileName\":\"%s\",\"isPublic\":true,\"textures\":{\"SKIN\":{\"url\":\"%s\"}}}"; private static final String JSON_CAPE = "{\"timestamp\":%d,\"profileId\":\"%s\",\"profileName\":\"%s\",\"isPublic\":true,\"textures\":{\"SKIN\":{\"url\":\"%s\"},\"CAPE\":{\"url\":\"%s\"}}}"; - private static Gson gson = new GsonBuilder().disableHtmlEscaping().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).registerTypeAdapter(GameProfile.class, new GameProfileSerializer()).registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create(); + private static final Gson gson = new GsonBuilder().disableHtmlEscaping().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).registerTypeAdapter(GameProfile.class, new GameProfileSerializer()).registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create(); - private static HashMap cache = new HashMap<>(); + private static final HashMap cache = new HashMap<>(); private static long cacheTime = -1; @@ -38,28 +38,13 @@ public class GameProfileBuilder { * Don't run in main thread! * * Fetches the GameProfile from the Mojang servers - * * @param uuid The player uuid * @return The GameProfile * @throws IOException If something wents wrong while fetching * @see GameProfile */ public static GameProfile fetch(UUID uuid) throws IOException { - return fetch(uuid, false); - } - - /** - * Don't run in main thread! - * - * Fetches the GameProfile from the Mojang servers - * @param uuid The player uuid - * @param forceNew If true the cache is ignored - * @return The GameProfile - * @throws IOException If something wents wrong while fetching - * @see GameProfile - */ - public static GameProfile fetch(UUID uuid, boolean forceNew) throws IOException { - if (!forceNew && cache.containsKey(uuid) && cache.get(uuid).isValid()) { + if (!false && cache.containsKey(uuid) && cache.get(uuid).isValid()) { return cache.get(uuid).profile; } else { HttpURLConnection connection = (HttpURLConnection) new URL(String.format(SERVICE_URL, UUIDTypeAdapter.fromUUID(uuid))).openConnection(); @@ -72,7 +57,7 @@ public class GameProfileBuilder { cache.put(uuid, new CachedProfile(result)); return result; } else { - if (!forceNew && cache.containsKey(uuid)) { + if (!false && cache.containsKey(uuid)) { return cache.get(uuid).profile; } JsonObject error = (JsonObject) new JsonParser().parse(new BufferedReader(new InputStreamReader(connection.getErrorStream())).readLine()); @@ -108,7 +93,7 @@ public class GameProfileBuilder { GameProfile profile = new GameProfile(uuid, name); boolean cape = capeUrl != null && !capeUrl.isEmpty(); - List args = new ArrayList(); + List args = new ArrayList<>(); args.add(System.currentTimeMillis()); args.add(UUIDTypeAdapter.fromUUID(uuid)); args.add(name); @@ -157,15 +142,15 @@ public class GameProfileBuilder { private static class CachedProfile { - private long timestamp = System.currentTimeMillis(); - private GameProfile profile; + private final long timestamp = System.currentTimeMillis(); + private final GameProfile profile; public CachedProfile(GameProfile profile) { this.profile = profile; } public boolean isValid() { - return cacheTime < 0 ? true : (System.currentTimeMillis() - timestamp) < cacheTime; + return cacheTime < 0 || (System.currentTimeMillis() - timestamp) < cacheTime; } } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/utils/Maths.java b/src/main/java/eu/univento/core/api/utils/Maths.java index 7dda43f..8dd0922 100644 --- a/src/main/java/eu/univento/core/api/utils/Maths.java +++ b/src/main/java/eu/univento/core/api/utils/Maths.java @@ -6,7 +6,7 @@ import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; -public final class Maths +final class Maths { public static final float nanoToSec = 1.0E-009F; public static final float FLOAT_ROUNDING_ERROR = 1.0E-006F; @@ -18,31 +18,31 @@ public final class Maths public static final float radDeg = 57.295776F; public static final float degreesToRadians = 0.01745329F; public static final float degRad = 0.01745329F; - static final int ATAN2_DIM = (int)Math.sqrt(16384.0D); + private static final int ATAN2_DIM = (int)Math.sqrt(16384.0D); private static final float INV_ATAN2_DIM_MINUS_1 = 1.0F / (ATAN2_DIM - 1); - public static Random random = new Random(); + private static final Random random = new Random(); - public static final float sin(float radians) { + public static float sin(float radians) { return Sin.table[((int)(radians * 2607.5945F) & 0x3FFF)]; } - public static final float cos(float radians) + public static float cos(float radians) { return Sin.table[((int)((radians + 1.570796F) * 2607.5945F) & 0x3FFF)]; } - public static final float sinDeg(float degrees) + public static float sinDeg(float degrees) { return Sin.table[((int)(degrees * 45.511112F) & 0x3FFF)]; } - public static final float cosDeg(float degrees) + public static float cosDeg(float degrees) { return Sin.table[((int)((degrees + 90.0F) * 45.511112F) & 0x3FFF)]; } - public static final float atan2(float y, float x) + public static float atan2(float y, float x) { float mul; float add; @@ -74,37 +74,37 @@ public final class Maths return (Atan2.table[(yi * ATAN2_DIM + xi)] + add) * mul; } - public static final int random(int range) + public static int random(int range) { return random.nextInt(range + 1); } - public static final int random(int start, int end) + public static int random(int start, int end) { return start + random.nextInt(end - start + 1); } - public static final boolean randomBoolean() + public static boolean randomBoolean() { return random.nextBoolean(); } - public static final boolean randomBoolean(float chance) + public static boolean randomBoolean(float chance) { return random() < chance; } - public static final float random() + private static float random() { return random.nextFloat(); } - public static final float random(float range) + public static float random(float range) { return random.nextFloat() * range; } - public static final float random(float start, float end) + public static float random(float start, float end) { return start + random.nextFloat() * (end - start); } diff --git a/src/main/java/eu/univento/core/api/utils/NettyInjection.java b/src/main/java/eu/univento/core/api/utils/NettyInjection.java new file mode 100644 index 0000000..66fd53c --- /dev/null +++ b/src/main/java/eu/univento/core/api/utils/NettyInjection.java @@ -0,0 +1,227 @@ +package eu.univento.core.api.utils; + +import eu.univento.core.api.utils.reflection.IReflection; +import io.netty.channel.*; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.plugin.Plugin; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * -== NettyInjection ==- + * + * This library was created by @Ingrim4 and allows you to inject a handler inside a channel of a PlayerConnection.class to modify or avoid packets + * You need my IReflection class -> http://bit.ly/IReflect + * You are welcome to use it and redistribute it under the following conditions: + * * Don't claim this class as your own + * * Don't remove this disclaimer + * + * @author Ingrim4 + * @version 1.2 + */ + +public class NettyInjection { + + private static final Class CLASS_CRAFTPLAYER = IReflection.getClass(IReflection.ServerPacket.CRAFTBUKKIT_PACKAGE, "entity.CraftPlayer"); + private static final Class CLASS_ENTITY = IReflection.getClass(IReflection.ServerPacket.MINECRAFT_PACKAGE, "Entity"); + private static final Class CLASS_ENTITYPLAYER = IReflection.getClass(IReflection.ServerPacket.MINECRAFT_PACKAGE, "EntityPlayer"); + private static final Class CLASS_PLAYERCONNECTION = IReflection.getClass(IReflection.ServerPacket.MINECRAFT_PACKAGE, "PlayerConnection"); + private static final Class CLASS_NETWORKMANAGER = IReflection.getClass(IReflection.ServerPacket.MINECRAFT_PACKAGE, "NetworkManager"); + private static final IReflection.FieldAccessor FIELD_CRAFTPLAYER_ENTITY = IReflection.getField(NettyInjection.CLASS_CRAFTPLAYER, NettyInjection.CLASS_ENTITY, 0); + private static final IReflection.FieldAccessor FIELD_ENTITYPLAYER_PLAYERCONNECTION = IReflection.getField(NettyInjection.CLASS_ENTITYPLAYER, NettyInjection.CLASS_PLAYERCONNECTION, 0); + private static final IReflection.FieldAccessor FIELD_PLAYERCONNECTION_NETWORKMANAGER = IReflection.getField(NettyInjection.CLASS_PLAYERCONNECTION, NettyInjection.CLASS_NETWORKMANAGER, 0); + private static final IReflection.FieldAccessor FIELD_NETWORKMANAGER_CHANNEL = IReflection.getField(NettyInjection.CLASS_NETWORKMANAGER, Channel.class, 0); + + private static final Class CLASS_GAMEPROFILE = IReflection.getClass(IReflection.ServerPacket.MOJANG_AUTHLIB, "GameProfile"); + private static final IReflection.FieldAccessor FIELD_GAMEPROFILE_NAME = IReflection.getField(NettyInjection.CLASS_GAMEPROFILE, String.class, 0); + + private static final Class CLASS_PACKERLOGININSTART = IReflection.getClass(IReflection.ServerPacket.MINECRAFT_PACKAGE, "PacketLoginInStart"); + private static final IReflection.FieldAccessor FIELD_PACKERLOGININSTART_GAMEPROFILE = IReflection.getField(NettyInjection.CLASS_PACKERLOGININSTART, NettyInjection.CLASS_GAMEPROFILE, 0); + + private static final Class CLASS_CRAFTSERVER = IReflection.getClass(IReflection.ServerPacket.CRAFTBUKKIT_PACKAGE, "CraftServer"); + private static final Class CLASS_MINECRAFTSERVER = IReflection.getClass(IReflection.ServerPacket.MINECRAFT_PACKAGE, "MinecraftServer"); + private static final Class CLASS_SERVERCONNECTION = IReflection.getClass(IReflection.ServerPacket.MINECRAFT_PACKAGE, "ServerConnection"); + private static final IReflection.FieldAccessor FIELD_CRAFTSERVER_MINECRAFTSERVER = IReflection.getField(NettyInjection.CLASS_CRAFTSERVER, NettyInjection.CLASS_MINECRAFTSERVER, 0); + private static final IReflection.FieldAccessor FIELD_MINECRAFTSERVER_SERVERCONNECTION = IReflection.getField(NettyInjection.CLASS_MINECRAFTSERVER, NettyInjection.CLASS_SERVERCONNECTION, 0); + private static final IReflection.FieldAccessor FIELD_SERVERCONNECTION_CHANNELFUTURE = IReflection.getField(NettyInjection.CLASS_SERVERCONNECTION, List.class, 0); + + private String handlerName = "nettyinjection_default"; + private Map handlerList = new HashMap(); + private Listener listener; + + private final HashMap playerChannel = new HashMap(); + + private final List globalChannel = new ArrayList(); + private ChannelInboundHandlerAdapter globalHandler; + + public interface PacketHandler { + + public default Object onPacketIn(Player sender, Channel channel, Object packet) { + return packet; + } + + public default Object onPacketOut(Player target, Channel channel, Object packet) { + return packet; + } + + public default void exceptionCaught(Player player, Channel channel,Throwable throwable) { } + } + + public NettyInjection(Plugin plugin, String handlerName) { + this.handlerName = "inject_" + handlerName; + + Bukkit.getPluginManager().registerEvents(this.listener = new Listener() { + @EventHandler + public final void onPlayerLogin(PlayerLoginEvent event) { + NettyInjection.this.inject(event.getPlayer()); + } + + @EventHandler + public void onDisabled(PluginDisableEvent event) { + if (event.getPlugin().equals(plugin)) + NettyInjection.this.disable(); + } + }, plugin); + + ChannelInitializer last = new ChannelInitializer() { + @Override + protected void initChannel(Channel channel) throws Exception { + NettyInjection.this.injectChannel(channel); + } + }; + + ChannelInitializer first = new ChannelInitializer() { + @Override + protected void initChannel(Channel channel) throws Exception { + channel.pipeline().addLast(last); + } + }; + + this.globalHandler = new ChannelInboundHandlerAdapter() { + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + ((Channel) msg).pipeline().addFirst(first); + super.channelRead(ctx, msg); + } + }; + + this.registerGlobalChannel(); + + for (Player player : Bukkit.getOnlinePlayers()) + this.inject(player); + } + + @SuppressWarnings("unchecked") + private final void registerGlobalChannel() { + Object server = NettyInjection.FIELD_CRAFTSERVER_MINECRAFTSERVER.get(Bukkit.getServer()); + Object connection = NettyInjection.FIELD_MINECRAFTSERVER_SERVERCONNECTION.get(server); + List channelFuture = (List) FIELD_SERVERCONNECTION_CHANNELFUTURE.get(connection); + for (Object item : channelFuture) { + if (!ChannelFuture.class.isInstance(item)) + break; + Channel channel = ((ChannelFuture) item).channel(); + this.globalChannel.add(channel); + channel.pipeline().addFirst("NettyInjectionGlobal", this.globalHandler); + } + } + + private final void unregisterGlobalChannel() { + for (Channel global : this.globalChannel) { + final ChannelPipeline pipe = global.pipeline(); + global.eventLoop().execute(() -> pipe.remove("NettyInjectionGlobal")); + } + } + + public final void addHandler(String name, PacketHandler handler) { + this.handlerList.put(name, handler); + } + + public final void removeHandler(String name) { + if (this.handlerList.containsKey(name)) + this.handlerList.remove(name); + } + + public final void inject(Player player) { + this.injectChannel(this.getChannel(player)).player = player; + } + + public final void uninject(Player player) { + this.uninjectChannel(this.getChannel(player)); + } + + private final Channel getChannel(Player player) { + Channel channel = this.playerChannel.get(player.getName()); + if (channel == null) { + channel = FIELD_NETWORKMANAGER_CHANNEL.get(FIELD_PLAYERCONNECTION_NETWORKMANAGER.get(FIELD_ENTITYPLAYER_PLAYERCONNECTION.get(FIELD_CRAFTPLAYER_ENTITY.get(player)))); + this.playerChannel.put(player.getName(), channel); + } + return channel; + } + + private final PacketInjection injectChannel(Channel channel) { + try { + PacketInjection handel = (PacketInjection) channel.pipeline().get(this.handlerName); + if (handel == null) { + handel = new PacketInjection(); + channel.pipeline().addBefore("packet_handler", this.handlerName, handel); + } + return handel; + } catch (Exception e) { + return (PacketInjection) channel.pipeline().get(this.handlerName); + } + } + + private final void uninjectChannel(Channel channel) { + Object handel = channel.pipeline().get(this.handlerName); + if (handel != null) + channel.pipeline().remove(this.handlerName); + } + + public final void disable() { + for (Player player : Bukkit.getOnlinePlayers()) + this.uninject(player); + HandlerList.unregisterAll(this.listener); + this.unregisterGlobalChannel(); + } + + private class PacketInjection extends ChannelDuplexHandler { + + public Player player; + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (CLASS_PACKERLOGININSTART.isInstance(msg)) + NettyInjection.this.playerChannel.put(FIELD_GAMEPROFILE_NAME.get(FIELD_PACKERLOGININSTART_GAMEPROFILE.get(msg)), ctx.channel()); + for (PacketHandler handel : NettyInjection.this.handlerList.values()) { + if (msg == null) + break; + msg = handel.onPacketIn(this.player, ctx.channel(), msg); + } + if (msg != null) + super.channelRead(ctx, msg); + } + + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + for (PacketHandler handel : NettyInjection.this.handlerList.values()) + msg = handel.onPacketOut(this.player, ctx.channel(), msg); + super.write(ctx, msg, promise); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) throws Exception { + for(PacketHandler handel : NettyInjection.this.handlerList.values()) + handel.exceptionCaught(this.player, ctx.channel(), throwable); + super.exceptionCaught(ctx, throwable); + } + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/utils/RandomCollection.java b/src/main/java/eu/univento/core/api/utils/RandomCollection.java index 6c792a9..cd99bae 100644 --- a/src/main/java/eu/univento/core/api/utils/RandomCollection.java +++ b/src/main/java/eu/univento/core/api/utils/RandomCollection.java @@ -4,9 +4,9 @@ import java.util.NavigableMap; import java.util.Random; import java.util.TreeMap; -public class RandomCollection +class RandomCollection { - private final NavigableMap map = new TreeMap(); + private final NavigableMap map = new TreeMap<>(); private final Random random; private double total = 0.0D; @@ -14,19 +14,19 @@ public class RandomCollection this(new Random()); } - public RandomCollection(Random random) { + private RandomCollection(Random random) { this.random = random; } public void add(double weight, E result) { if (weight <= 0.0D) return; this.total += weight; - this.map.put(Double.valueOf(this.total), result); + this.map.put(this.total, result); } public E next() { double value = this.random.nextDouble() * this.total; - return this.map.ceilingEntry(Double.valueOf(value)).getValue(); + return this.map.ceilingEntry(value).getValue(); } public E random() { @@ -36,6 +36,6 @@ public class RandomCollection value = this.random.nextDouble() * this.total; } - return this.map.ceilingEntry(Double.valueOf(value)).getValue(); + return this.map.ceilingEntry(value).getValue(); } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/utils/UUIDFetcher.java b/src/main/java/eu/univento/core/api/utils/UUIDFetcher.java index 82f7e7e..33be615 100644 --- a/src/main/java/eu/univento/core/api/utils/UUIDFetcher.java +++ b/src/main/java/eu/univento/core/api/utils/UUIDFetcher.java @@ -28,14 +28,14 @@ public class UUIDFetcher{ public static final long FEBRUARY_2015 = 1422748800000L; - private static Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create(); + private static final Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create(); //private static final String UUID_URL = "https://api.mojang.com/users/profiles/minecraft/%s?at=%d"; private static final String UUID_URL = "https://mcapi.de/api/user/%s"; private static final String NAME_URL = "https://api.mojang.com/user/profiles/%s/names"; - private static Map uuidCache = new HashMap<>(); - private static Map nameCache = new HashMap<>(); - private static ExecutorService pool = Executors.newCachedThreadPool(); + private static final Map uuidCache = new HashMap<>(); + private static final Map nameCache = new HashMap<>(); + private static final ExecutorService pool = Executors.newCachedThreadPool(); private String name; private UUID id; @@ -78,7 +78,7 @@ public class UUIDFetcher{ * @param timestamp Time when the player had this name in milliseconds * @see UUIDFetcher#FEBRUARY_2015 */ - public static UUID getUUIDAt(String name, long timestamp) { + private static UUID getUUIDAt(String name, long timestamp) { name = name.toLowerCase(); if (uuidCache.containsKey(name)) { return uuidCache.get(name); diff --git a/src/main/java/eu/univento/core/api/utils/Vectors.java b/src/main/java/eu/univento/core/api/utils/Vectors.java index b5606d4..617978c 100644 --- a/src/main/java/eu/univento/core/api/utils/Vectors.java +++ b/src/main/java/eu/univento/core/api/utils/Vectors.java @@ -2,9 +2,9 @@ package eu.univento.core.api.utils; import org.bukkit.util.Vector; -public final class Vectors +final class Vectors { - public static final Vector rotateAroundAxisX(Vector v, double angle) + private static Vector rotateAroundAxisX(Vector v, double angle) { double cos = Math.cos(angle); double sin = Math.sin(angle); @@ -13,7 +13,7 @@ public final class Vectors return v.setY(y).setZ(z); } - public static final Vector rotateAroundAxisY(Vector v, double angle) + private static Vector rotateAroundAxisY(Vector v, double angle) { double cos = Math.cos(angle); double sin = Math.sin(angle); @@ -22,7 +22,7 @@ public final class Vectors return v.setX(x).setZ(z); } - public static final Vector rotateAroundAxisZ(Vector v, double angle) + private static Vector rotateAroundAxisZ(Vector v, double angle) { double cos = Math.cos(angle); double sin = Math.sin(angle); @@ -31,7 +31,7 @@ public final class Vectors return v.setX(x).setY(y); } - public static final Vector rotateVector(Vector v, double angleX, double angleY, double angleZ) + public static Vector rotateVector(Vector v, double angleX, double angleY, double angleZ) { rotateAroundAxisX(v, angleX); rotateAroundAxisY(v, angleY); @@ -39,7 +39,7 @@ public final class Vectors return v; } - public static final double angleToXAxis(Vector vector) { + public static double angleToXAxis(Vector vector) { return Math.atan2(vector.getX(), vector.getY()); } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/api/utils/reflection/ArrayWrapper.java b/src/main/java/eu/univento/core/api/utils/reflection/ArrayWrapper.java index ff23c08..912a363 100644 --- a/src/main/java/eu/univento/core/api/utils/reflection/ArrayWrapper.java +++ b/src/main/java/eu/univento/core/api/utils/reflection/ArrayWrapper.java @@ -18,7 +18,7 @@ import java.util.Collection; * @see Arrays */ -public final class ArrayWrapper { +final class ArrayWrapper { /** @@ -26,6 +26,7 @@ public final class ArrayWrapper { * * @param elements The elements of the array. */ + @SafeVarargs public ArrayWrapper(E... elements) { setArray(elements); } @@ -46,7 +47,7 @@ public final class ArrayWrapper { * * @param array The new wrapped array. */ - public void setArray(E[] array) { + private void setArray(E[] array) { Validate.notNull(array, "The array must not be null."); _array = array; } diff --git a/src/main/java/eu/univento/core/api/utils/reflection/IReflection.java b/src/main/java/eu/univento/core/api/utils/reflection/IReflection.java index 841fe5f..464f735 100644 --- a/src/main/java/eu/univento/core/api/utils/reflection/IReflection.java +++ b/src/main/java/eu/univento/core/api/utils/reflection/IReflection.java @@ -6,6 +6,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -25,27 +26,27 @@ public class IReflection { public interface ConstructorAccessor { - public Object newInstance(Object... args); + Object newInstance(Object... args); - public Constructor getConstructor(); + Constructor getConstructor(); } public interface MethodAccessor { - public Object invoke(Object target, Object... args); + Object invoke(Object target, Object... args); - public Method getMehtod(); + Method getMehtod(); } public interface FieldAccessor { - public T get(Object target); + T get(Object target); - public void set(Object target, Object value); + void set(Object target, Object value); - public Field getField(); + Field getField(); } @@ -58,7 +59,7 @@ public class IReflection { return null; } - public static ConstructorAccessor getConstructor(Class clazz, Class... parameterTypes) { + private static ConstructorAccessor getConstructor(Class clazz, Class... parameterTypes) { Class[] p = DataType.convertToPrimitive(parameterTypes); for (Constructor c : clazz.getDeclaredConstructors()) if (DataType.equalsArray(DataType.convertToPrimitive(c.getParameterTypes()), p)) { @@ -95,7 +96,7 @@ public class IReflection { return IReflection.getMethod(target, methodName, null, parameterTypes); } - public static MethodAccessor getMethod(Class target, String methodName, Class returnType, Class... parameterTypes) { + private static MethodAccessor getMethod(Class target, String methodName, Class returnType, Class... parameterTypes) { Class[] primitiveParameter = DataType.convertToPrimitive(parameterTypes); for (Method method : target.getDeclaredMethods()) if ((methodName == null || method.getName().equals(methodName)) && (returnType == null || method.getReturnType().equals(returnType)) && (primitiveParameter.length == 0 || DataType.equalsArray(DataType.convertToPrimitive(method.getParameterTypes()), primitiveParameter))) { @@ -124,7 +125,7 @@ public class IReflection { if (target.getSuperclass() != null) return IReflection.getMethod(target.getSuperclass(), methodName, returnType, parameterTypes); - throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, parameterTypes)); + throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.toString(parameterTypes))); } public static FieldAccessor getField(Class target, String fieldName) { @@ -182,7 +183,7 @@ public class IReflection { Integer.class), LONG(long.class, Long.class), CHARACTER(char.class, Character.class), FLOAT(float.class, Float.class), DOUBLE(double.class, Double.class), BOOLEAN(boolean.class, Boolean.class); - private static final Map, DataType> CLASS_MAP = new HashMap, DataType>(); + private static final Map, DataType> CLASS_MAP = new HashMap<>(); private final Class primitive; private final Class reference; @@ -193,7 +194,7 @@ public class IReflection { } } - private DataType(Class primitive, Class reference) { + DataType(Class primitive, Class reference) { this.primitive = primitive; this.reference = reference; } diff --git a/src/main/java/eu/univento/core/api/utils/reflection/Reflection.java b/src/main/java/eu/univento/core/api/utils/reflection/Reflection.java index 8710c3b..5668c60 100644 --- a/src/main/java/eu/univento/core/api/utils/reflection/Reflection.java +++ b/src/main/java/eu/univento/core/api/utils/reflection/Reflection.java @@ -13,7 +13,7 @@ import org.bukkit.Bukkit; * A class containing static utility methods and caches which are intended as reflective conveniences. * Unless otherwise noted, upon failure methods will return {@code null}. */ -public final class Reflection { +final class Reflection { private static String _versionString; @@ -27,7 +27,7 @@ public final class Reflection { * * @return The version string of the OBC and NMS packages, including the trailing dot. */ - public synchronized static String getVersion() { + private synchronized static String getVersion() { if (_versionString == null) { if (Bukkit.getServer() == null) { // The server hasn't started, static initializer call? @@ -135,7 +135,7 @@ public final class Reflection { } } - private static final Map, Map> _loadedFields = new HashMap, Map>(); + private static final Map, Map> _loadedFields = new HashMap<>(); /** * Retrieves a {@link Field} instance declared by the specified class with the specified name. @@ -208,8 +208,8 @@ public final class Reflection { * @param args The formal argument types of the method. * @return A method object with the specified name declared by the specified class. */ - public synchronized static Method getMethod(Class clazz, String name, - Class... args) { + private synchronized static Method getMethod(Class clazz, String name, + Class... args) { if (!_loadedMethods.containsKey(clazz)) { _loadedMethods.put(clazz, new HashMap<>()); } diff --git a/src/main/java/eu/univento/core/api/utils/reflection/ReflectionUtils.java b/src/main/java/eu/univento/core/api/utils/reflection/ReflectionUtils.java index 1eacc33..d62e0ab 100644 --- a/src/main/java/eu/univento/core/api/utils/reflection/ReflectionUtils.java +++ b/src/main/java/eu/univento/core/api/utils/reflection/ReflectionUtils.java @@ -60,7 +60,7 @@ public final class ReflectionUtils { * @return The constructor of the desired target class with the specified parameter types * @throws NoSuchMethodException If the desired constructor with the specified parameter types cannot be found * @throws ClassNotFoundException ClassNotFoundException If the desired target class with the specified name and package cannot be found - * @see #getClass(String, PackageType) + * @see String, PackageType) * @see #getConstructor(Class, Class...) */ public static Constructor getConstructor(String className, PackageType packageType, Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { @@ -79,7 +79,7 @@ public final class ReflectionUtils { * @throws InvocationTargetException If the desired constructor cannot be invoked * @throws NoSuchMethodException If the desired constructor with the specified arguments cannot be found */ - public static Object instantiateObject(Class clazz, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { + private static Object instantiateObject(Class clazz, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { return getConstructor(clazz, DataType.getPrimitive(arguments)).newInstance(arguments); } @@ -96,7 +96,7 @@ public final class ReflectionUtils { * @throws InvocationTargetException If the desired constructor cannot be invoked * @throws NoSuchMethodException If the desired constructor with the specified arguments cannot be found * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found - * @see #getClass(String, PackageType) + * @see String, PackageType) * @see #instantiateObject(Class, Object...) */ public static Object instantiateObject(String className, PackageType packageType, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { @@ -135,7 +135,7 @@ public final class ReflectionUtils { * @return The method of the desired target class with the specified name and parameter types * @throws NoSuchMethodException If the desired method of the desired target class with the specified name and parameter types cannot be found * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found - * @see #getClass(String, PackageType) + * @see String, PackageType) * @see #getMethod(Class, String, Class...) */ public static Method getMethod(String className, PackageType packageType, String methodName, Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { @@ -157,7 +157,7 @@ public final class ReflectionUtils { * @see DataType#getPrimitive(Object[]) */ public static Object invokeMethod(Object instance, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { - return getMethod(instance.getClass(), methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); + return getMethod(instance.getClass(), methodName,DataType.getPrimitive(arguments)).invoke(instance, arguments); } /** @@ -175,7 +175,7 @@ public final class ReflectionUtils { * @see #getMethod(Class, String, Class...) * @see DataType#getPrimitive(Object[]) */ - public static Object invokeMethod(Object instance, Class clazz, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { + private static Object invokeMethod(Object instance, Class clazz, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { return getMethod(clazz, methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); } @@ -193,7 +193,7 @@ public final class ReflectionUtils { * @throws InvocationTargetException If the desired method cannot be invoked on the target object * @throws NoSuchMethodException If the desired method of the desired target class with the specified name and arguments cannot be found * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found - * @see #getClass(String, PackageType) + * @see String, PackageType) * @see #invokeMethod(Object, Class, String, Object...) */ public static Object invokeMethod(Object instance, String className, PackageType packageType, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { @@ -210,7 +210,7 @@ public final class ReflectionUtils { * @throws NoSuchFieldException If the desired field of the given class cannot be found * @throws SecurityException If the desired field cannot be made accessible */ - public static Field getField(Class clazz, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException { + private static Field getField(Class clazz, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException { Field field = declared ? clazz.getDeclaredField(fieldName) : clazz.getField(fieldName); field.setAccessible(true); return field; @@ -220,7 +220,6 @@ public final class ReflectionUtils { * Returns a field of a desired class with the given name * * @param className Name of the desired target class - * @param packageType Package where the desired target class is located * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field * @return The field of the desired target class with the specified name @@ -229,8 +228,8 @@ public final class ReflectionUtils { * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found * @see #getField(Class, boolean, String) */ - public static Field getField(String className, PackageType packageType, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException { - return getField(packageType.getClass(className), declared, fieldName); + public static Field getField(String className, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException { + return getField(PackageType.MINECRAFT_SERVER.getClass("EntityPlayer"), false, "playerConnection"); } /** @@ -247,7 +246,7 @@ public final class ReflectionUtils { * @throws SecurityException If the desired field cannot be made accessible * @see #getField(Class, boolean, String) */ - public static Object getValue(Object instance, Class clazz, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + private static Object getValue(Object instance, Class clazz, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { return getField(clazz, declared, fieldName).get(instance); } @@ -302,7 +301,7 @@ public final class ReflectionUtils { * @throws SecurityException If the desired field cannot be made accessible * @see #getField(Class, boolean, String) */ - public static void setValue(Object instance, Class clazz, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + private static void setValue(Object instance, Class clazz, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { getField(clazz, declared, fieldName).set(instance, value); } @@ -330,7 +329,6 @@ public final class ReflectionUtils { * Sets the value of a field with the given name of an object * * @param instance Target object - * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field * @param value New value * @throws IllegalArgumentException If the type of the value does not match the type of the desired field @@ -339,8 +337,8 @@ public final class ReflectionUtils { * @throws SecurityException If the desired field cannot be made accessible * @see #setValue(Object, Class, boolean, String, Object) */ - public static void setValue(Object instance, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { - setValue(instance, instance.getClass(), declared, fieldName, value); + public static void setValue(Object instance, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + setValue(instance, instance.getClass(), true, fieldName, value); } /** @@ -380,7 +378,7 @@ public final class ReflectionUtils { * * @param path Path of the package */ - private PackageType(String path) { + PackageType(String path) { this.path = path; } @@ -390,7 +388,7 @@ public final class ReflectionUtils { * @param parent Parent package of the package * @param path Path of the package */ - private PackageType(PackageType parent, String path) { + PackageType(PackageType parent, String path) { this(parent + "." + path); } @@ -448,7 +446,7 @@ public final class ReflectionUtils { DOUBLE(double.class, Double.class), BOOLEAN(boolean.class, Boolean.class); - private static final Map, DataType> CLASS_MAP = new HashMap, DataType>(); + private static final Map, DataType> CLASS_MAP = new HashMap<>(); private final Class primitive; private final Class reference; @@ -466,7 +464,7 @@ public final class ReflectionUtils { * @param primitive Primitive class of this data type * @param reference Reference class of this data type */ - private DataType(Class primitive, Class reference) { + DataType(Class primitive, Class reference) { this.primitive = primitive; this.reference = reference; } @@ -554,7 +552,7 @@ public final class ReflectionUtils { /** * Returns the primitive class array of the given object array * - * @param object Given object array + * @param objects Given object array * @return The primitive class array */ public static Class[] getPrimitive(Object[] objects) { @@ -569,7 +567,7 @@ public final class ReflectionUtils { /** * Returns the reference class array of the given object array * - * @param object Given object array + * @param objects Given object array * @return The reference class array */ public static Class[] getReference(Object[] objects) { diff --git a/src/main/java/eu/univento/core/commands/Build.java b/src/main/java/eu/univento/core/commands/Build.java index 701381f..be5ea09 100644 --- a/src/main/java/eu/univento/core/commands/Build.java +++ b/src/main/java/eu/univento/core/commands/Build.java @@ -24,7 +24,7 @@ public class Build extends AutoCommand{ /** * player who can build */ - private static HashMap players = new HashMap<>(); + private static final HashMap players = new HashMap<>(); /** * @return player that can build @@ -35,7 +35,6 @@ public class Build extends AutoCommand{ /** * @param plugin main class - * @param command command to execute * @param description describes the command * @param aliases aliases of command */ @@ -56,7 +55,6 @@ public class Build extends AutoCommand{ p.getInventory().setContents(content); players.remove(p); p.setGameMode(ServerSettings.getGameMode()); - }else { players.put(p, p.getInventory().getContents()); p.sendMessage(msgs.PREFIX() + msgs.Core_BUILD_ON()); diff --git a/src/main/java/eu/univento/core/commands/GameMode.java b/src/main/java/eu/univento/core/commands/GameMode.java index dc5e878..1c4f7ef 100644 --- a/src/main/java/eu/univento/core/commands/GameMode.java +++ b/src/main/java/eu/univento/core/commands/GameMode.java @@ -21,7 +21,6 @@ public class GameMode extends AutoCommand{ /** * @param plugin main class * @param command command to execute - * @param description describes the command * @param aliases aliases of command */ public GameMode(Core plugin, String command, String description, String... aliases) { diff --git a/src/main/java/eu/univento/core/commands/Nick.java b/src/main/java/eu/univento/core/commands/Nick.java index ecb157f..22be14d 100644 --- a/src/main/java/eu/univento/core/commands/Nick.java +++ b/src/main/java/eu/univento/core/commands/Nick.java @@ -59,7 +59,6 @@ public class Nick extends AutoCommand{ @Override public List tabComplete(CommandSender sender, String label, String[] args) { - return null; } diff --git a/src/main/java/eu/univento/core/commands/SetRank.java b/src/main/java/eu/univento/core/commands/SetRank.java index 15fdfa7..304e5d1 100644 --- a/src/main/java/eu/univento/core/commands/SetRank.java +++ b/src/main/java/eu/univento/core/commands/SetRank.java @@ -19,12 +19,6 @@ import java.util.stream.Collectors; */ public class SetRank extends AutoCommand{ - /** - * @param plugin main class - * @param command command to execute - * @param description describes the command - * @param aliases aliases of command - */ public SetRank(Core plugin, String command, String description, String... aliases) { super(plugin, command, description, aliases); } @@ -101,9 +95,7 @@ public class SetRank extends AutoCommand{ } private void refreshTablist() { - Bukkit.getScheduler().runTaskLater(Core.getInstance(), () -> { - Core.getOnlinePlayers().forEach(CustomPlayer::refreshTablist); - }, 10L); + Bukkit.getScheduler().runTaskLater(Core.getInstance(), () -> Core.getOnlinePlayers().forEach(CustomPlayer::refreshTablist), 10L); } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/commands/SystemInfo.java b/src/main/java/eu/univento/core/commands/SystemInfo.java index 198114a..15a914f 100644 --- a/src/main/java/eu/univento/core/commands/SystemInfo.java +++ b/src/main/java/eu/univento/core/commands/SystemInfo.java @@ -44,13 +44,16 @@ public class SystemInfo extends AutoCommand{ e.printStackTrace(); } p.sendMessage("§6Spigot version: " + Bukkit.getVersion()); + p.sendMessage("§6Java version: " + System.getProperty("java.version")); + p.sendMessage("§6OS: " + System.getProperty("os.name")); + p.sendMessage("§6OS version: " + System.getProperty("os.version")); + p.sendMessage("§6OS architecture: " + System.getProperty("os.arch")); + p.sendMessage("§6User: " + System.getProperty("user.name")); p.sendMessage("§6used memory: " + (run.totalMemory() - run.freeMemory() / 1048576L) + " MB"); p.sendMessage("§6free memory: " + run.freeMemory() / 1048576L + " MB"); p.sendMessage("§6total memory: " + run.maxMemory() / 1048576L + " MB"); p.sendMessage("§6avaiable cores: " + run.availableProcessors()); - p.sendMessage("§6OS: " + System.getProperty("os.name")); - p.sendMessage("§6OS version: " + System.getProperty("os.version")); - p.sendMessage("§6OS architecture: " + System.getProperty("os.arch")); + p.sendMessage("§6System: " + System.getenv("COMPUTERNAME")); }else { p.sendMessage(msgs.NO_PERMS()); } diff --git a/src/main/java/eu/univento/core/commands/Timeout.java b/src/main/java/eu/univento/core/commands/Timeout.java new file mode 100644 index 0000000..8ded653 --- /dev/null +++ b/src/main/java/eu/univento/core/commands/Timeout.java @@ -0,0 +1,57 @@ +package eu.univento.core.commands; + +import eu.univento.core.Core; +import eu.univento.core.api.AutoCommand; +import eu.univento.core.api.languages.Messages; +import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.Rank; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +/** + * @author joethei + * @version 0.1 + * Created at 17:54 on 27.07.2016. + */ +public class Timeout extends AutoCommand { + + public Timeout(Core plugin, String command, String description, String... aliases) { + super(plugin, command, description, aliases); + } + + @Override + public boolean execute(CommandSender sender, String label, String[] args) { + if (sender instanceof Player) { + CustomPlayer p = CustomPlayer.getPlayer((Player) sender); + if (p.isAllowed(Rank.SrDeveloper)) { + if (args.length == 1) { + if (Bukkit.getPlayer(args[0]) != null) { + CustomPlayer t = CustomPlayer.getPlayer(args[0]); + if(Core.getTimeout().contains(p)) { + Core.getTimeout().remove(p); + }else{ + Core.getTimeout().add(p); + } + } else { + p.sendMessage(p.getMessage("Command.not_online")); + } + } else { + p.sendMessage("Nicht genug Argumente"); + } + } else { + p.sendMessage(p.getMessage("Command.no_perms")); + } + } else { + sender.sendMessage(Messages.Console.NOT_A_PLAYER); + } + return true; + } + + @Override + public List tabComplete(CommandSender sender, String label, String[] args) { + return null; + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/commands/Vanish.java b/src/main/java/eu/univento/core/commands/Vanish.java index 464df33..9680d0c 100644 --- a/src/main/java/eu/univento/core/commands/Vanish.java +++ b/src/main/java/eu/univento/core/commands/Vanish.java @@ -22,7 +22,7 @@ public class Vanish extends AutoCommand{ /** * contains vanished players */ - private static ArrayList players = new ArrayList(); + private static final ArrayList players = new ArrayList<>(); /** * @return vanished players */ diff --git a/src/main/java/eu/univento/core/listeners/Blocks.java b/src/main/java/eu/univento/core/listeners/Blocks.java index 89da870..7e1441c 100644 --- a/src/main/java/eu/univento/core/listeners/Blocks.java +++ b/src/main/java/eu/univento/core/listeners/Blocks.java @@ -50,4 +50,6 @@ public class Blocks implements Listener{ e.setBuildable(true); } + + } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/listeners/Chat.java b/src/main/java/eu/univento/core/listeners/Chat.java index 02ca58a..5cc809f 100644 --- a/src/main/java/eu/univento/core/listeners/Chat.java +++ b/src/main/java/eu/univento/core/listeners/Chat.java @@ -1,47 +1,132 @@ package eu.univento.core.listeners; +import eu.univento.core.Core; +import eu.univento.core.api.blocks.MiniBlock; +import eu.univento.core.api.customitems.swords.BestSwordEver; import eu.univento.core.api.languages.Messages; import eu.univento.core.api.player.CustomPlayer; import eu.univento.core.api.player.Rank; +import eu.univento.core.api.player.WarnReason; import eu.univento.core.api.server.ServerSettings; +import eu.univento.core.api.shop.ShopItem; +import eu.univento.core.api.shop.ShopMenu; +import eu.univento.core.api.shop.entity.ShopVillager; import net.md_5.bungee.api.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Villager; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; /** * manages chat + * * @author joethei * @version 1.0 */ -public class Chat implements Listener{ - - /** - * @param e AsyncPlayerChatEvent - */ - @EventHandler - public void onChat(AsyncPlayerChatEvent e) { - CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer().getName()); - Messages msgs = new Messages(p); - if(ServerSettings.isMute()) { - if(!p.isAllowed(Rank.Sound)) { - e.setCancelled(true); - p.sendMessage(msgs.PREFIX() + msgs.Core_SERVER_MUTED()); - } - } - String format; - if(p.isAllowed(Rank.Partner)) { - if(p.isNicked() && !ServerSettings.isLobby()) { - format = p.getPrefix() + p.getColor() + p.getDisplayName() + p.getSuffix() + ChatColor.translateAlternateColorCodes('&', e.getMessage()); - }else { - format = p.getPrefix() + p.getColor() + p.getDisplayName() + p.getSuffix() + ChatColor.translateAlternateColorCodes('&', e.getMessage()); - } - }else { - format = p.getPrefix() + p.getDisplayName() + p.getSuffix() + e.getMessage(); - } - if(format.contains("%")) format = format.replace("%", "%%"); - e.setFormat(format); +public class Chat implements Listener { - } + private List players = new LinkedList<>(); + private Map spam = new LinkedHashMap<>(); + private Map spamPlayers = new LinkedHashMap<>(); + + @EventHandler + public void onChat(AsyncPlayerChatEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer().getName()); + assert p != null; + //TODO: remove this, used for debugging + if (e.getMessage().equalsIgnoreCase("bestswordever")) { + new BestSwordEver(p).addItem(); + } + if (e.getMessage().equalsIgnoreCase("shopvillager")) { + ShopMenu menu = new ShopMenu(Core.getInstance(), "Shop Villager", ShopItem.TestItem); + new ShopVillager(Core.getInstance(), "Shop Villager", p.getLocation(), Villager.Profession.LIBRARIAN, menu); + } + if(e.getMessage().equalsIgnoreCase("miniblock")) { + new MiniBlock(p.getLocation(), new ItemStack(Material.GRASS), 1); + new MiniBlock(p.getEyeLocation(), new ItemStack(Material.DIAMOND_SWORD), 2); + new MiniBlock(p.getWorld().getSpawnLocation(), new ItemStack(Material.WOOL), 3); + } + + Messages msgs = p.getMessages(); + if (ServerSettings.isMute()) { + if (!p.isAllowed(Rank.Sound)) { + e.setCancelled(true); + p.sendMessage(msgs.PREFIX() + msgs.Core_SERVER_MUTED()); + } + } + if (p.isMuted()) { + e.setCancelled(true); + p.sendMessage(msgs.PREFIX() + msgs.Core_SERVER_MUTED()); + } + if (players.contains(p)) { + e.setCancelled(true); + p.sendMessage("§cDu musst dich bewegen bevor du chatten kannst"); + } + if(!spam.containsKey(p)) spam.put(p, System.currentTimeMillis()); + if(System.currentTimeMillis() - spam.get(p) < 5 * 20L) { + e.setCancelled(true); + p.sendMessage("Nicht spammen"); + spamPlayers.put(p, spamPlayers.get(p) + 1); + } + if(spamPlayers.get(p) > 100) { + p.warn(WarnReason.SPAM, null, "https://players.univento.eu/" + p.getUniqueId().toString() + "/chatlog"); + } + + char[] parts = e.getMessage().toCharArray(); + + int sum = 0; + for (char part : parts) { + sum += part; + } + double ratio = sum / parts.length; + int percent = (int)(100.0D * ratio); + + if(percent > 50) { + e.setCancelled(true); + p.sendMessage("§cKeine Caps verwenden"); + } + + String format; + if (p.isAllowed(Rank.Partner)) { + if (p.isNicked() && !ServerSettings.isLobby()) { + format = p.getPrefix() + p.getColor() + p.getDisplayName() + p.getSuffix() + ChatColor.translateAlternateColorCodes('&', e.getMessage()); + } else { + format = p.getPrefix() + p.getDisplayName() + p.getSuffix() + e.getMessage(); + } + if (format.contains("%")) format = format.replace("%", "%%"); + e.setFormat(format); + Core.getOnlinePlayers().stream().filter(player -> e.getMessage().toLowerCase().contains(player.getDisplayName().toLowerCase()) || e.getMessage().toLowerCase().contains(player.getName().toLowerCase())).forEach(player -> p.playSound(p.getEyeLocation(), Sound.BLOCK_NOTE_PLING, 100.0F, 1.0F)); + } + } + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + players.add(p); + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + if(players.contains(p)) players.remove(p); + if(spam.containsKey(p)) spam.remove(p); + } + + @EventHandler + public void onPlayerMove(PlayerMoveEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + if (players.contains(p)) players.remove(p); + } } \ No newline at end of file diff --git a/src/main/java/eu/univento/core/listeners/Events.java b/src/main/java/eu/univento/core/listeners/Events.java index a9cf524..476975e 100644 --- a/src/main/java/eu/univento/core/listeners/Events.java +++ b/src/main/java/eu/univento/core/listeners/Events.java @@ -4,7 +4,6 @@ import eu.univento.core.api.player.CustomPlayer; import eu.univento.core.api.server.ServerSettings; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryAction; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.server.ServerListPingEvent; @@ -17,7 +16,7 @@ public class Events implements Listener{ @EventHandler public void onServerListPing(ServerListPingEvent e) { - if(ServerSettings.isGame()) e.setMotd(ServerSettings.getPlayedGame().toString() + ";" + ServerSettings.getGameState()); + if(ServerSettings.isGame()) e.setMotd(ServerSettings.getServerType().toString() + ";" + ServerSettings.getGameState()); } @EventHandler diff --git a/src/main/java/eu/univento/core/listeners/JoinQuit.java b/src/main/java/eu/univento/core/listeners/JoinQuit.java index 6609ada..69124d8 100644 --- a/src/main/java/eu/univento/core/listeners/JoinQuit.java +++ b/src/main/java/eu/univento/core/listeners/JoinQuit.java @@ -1,7 +1,6 @@ package eu.univento.core.listeners; import eu.univento.core.Core; -import eu.univento.core.api.Title; import eu.univento.core.api.Utils; import eu.univento.core.api.player.*; import eu.univento.core.api.server.ServerSettings; @@ -15,12 +14,15 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerResourcePackStatusEvent; import org.bukkit.scoreboard.Team; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; /** * @author joethei @@ -28,6 +30,9 @@ import java.util.HashMap; */ public class JoinQuit implements Listener { + private List firstJoin = new LinkedList<>(); + private List loading = new LinkedList<>(); + @EventHandler public void onJoin(PlayerJoinEvent e) { CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); @@ -37,18 +42,18 @@ public class JoinQuit implements Listener { if (Vanish.getPlayers().contains(player)) { p.hidePlayer(player); } - if (Spectator.is(player)) { + if (SpectateManager.contains(player)) { p.hidePlayer(player); } } if (!p.hasPlayedBefore()) { - p.insertToDatabase(); + firstJoin.add(p); for (int i = 0; i <= 15; i++) { Utils.randomFirework(p.getEyeLocation()); } } - if(!p.isOnline()) { + if (!p.isOnline()) { HashMap labyModFeatures = new HashMap<>(); labyModFeatures.put(LabyMod.DAMAGEINDICATOR, false); labyModFeatures.put(LabyMod.MINIMAP_RADAR, false); @@ -72,16 +77,42 @@ public class JoinQuit implements Listener { p.setGameMode(ServerSettings.getGameMode()); p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); p.initScoreboard(); - Title.sendTabTitle(p, p.getMessages().Core_TAB_TITLE() + Bukkit.getServerName(), p.getMessages().TAB_PREFIX()); + p.sendTabHeaderAndFooter(p.getMessages().Core_TAB_TITLE() + Bukkit.getServerName(), p.getMessages().TAB_PREFIX()); if (p.isNicked() && !ServerSettings.isLobby()) { p.setNick(NickName.getRandomNick()); } - for(CustomPlayer player : Core.getOnlinePlayers()) { + for (CustomPlayer player : Core.getOnlinePlayers()) { p.getScoreboard().getTeam(player.getTeam().getName()).addEntry(player.getDisplayName()); player.getScoreboard().getTeam(p.getTeam().getName()).addEntry(p.getDisplayName()); } p.setCollidable(false); -} + + p.setStoryResourcePack(); + loading.add(p); + + } + + @EventHandler + public void onResourcePackStatus(PlayerResourcePackStatusEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + if(e.getStatus() == PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED) { + if(firstJoin.contains(p)) { + firstJoin.remove(p); + if(ServerSettings.isLobby()) { + //TODO: add story intro here. + } + } + loading.remove(p); + } + if(e.getStatus() == PlayerResourcePackStatusEvent.Status.FAILED_DOWNLOAD) { + p.sendMessage(p.getMessage("Pack.failed_download")); + Bukkit.getScheduler().runTaskLaterAsynchronously(Core.getInstance(), p::setStoryResourcePack, 10 * 20L); + } + if(e.getStatus() == PlayerResourcePackStatusEvent.Status.DECLINED) { + p.sendMessage(p.getMessage("Pack.declined")); + Bukkit.getScheduler().runTaskLaterAsynchronously(Core.getInstance(), p::setStoryResourcePack, 10 * 20L); + } + } @EventHandler public void onQuit(PlayerQuitEvent e) { diff --git a/src/main/java/eu/univento/core/listeners/NPCEvents.java b/src/main/java/eu/univento/core/listeners/NPCEvents.java new file mode 100644 index 0000000..89b97d8 --- /dev/null +++ b/src/main/java/eu/univento/core/listeners/NPCEvents.java @@ -0,0 +1,12 @@ +package eu.univento.core.listeners; + +import org.bukkit.event.Listener; + +/** + * @author joethei + * @version 0.1 + * Created at 17:24 on 27.07.2016. + */ +public class NPCEvents implements Listener { + +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/listeners/PluginMessenger.java b/src/main/java/eu/univento/core/listeners/PluginMessenger.java index 9c46183..6d3704d 100644 --- a/src/main/java/eu/univento/core/listeners/PluginMessenger.java +++ b/src/main/java/eu/univento/core/listeners/PluginMessenger.java @@ -3,8 +3,8 @@ package eu.univento.core.listeners; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import eu.univento.core.Core; -import eu.univento.core.antihack.Hack; import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.WarnReason; import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; @@ -28,10 +28,11 @@ public class PluginMessenger implements PluginMessageListener { p.sendMessage(p.getMessage("Prefix") + p.getMessage("Hack.WorldDownloader")); } if(channel.equals("WDL|CONTROL")) { - p.sendPluginMessage(Core.getInstance(), "WDL|CONTROL", createWDLPacket(false, 0, false, false, false, false)); + p.sendPluginMessage(Core.getInstance(), "WDL|CONTROL", createWDLPacket(0, false, false, false, false)); } if (channel.equals("PERMISSIONSREPL") && new String(data).contains("mod.worlddownloader")) { - p.warn(Hack.WDL); + //TODO: change to real warn reason + p.warn(WarnReason.SPAM, null, "https://players.univento.eu/" + p.getUniqueId().toString() + "/hacks"); p.sendMessage(p.getMessage("Prefix") + p.getMessage("Hack.WorldDownloader")); } if(channel.equals("5zig_Set")) { @@ -46,17 +47,17 @@ public class PluginMessenger implements PluginMessageListener { } } - private byte[] createWDLPacket(boolean globalIsEnabled, int saveRadius, boolean cacheChunks, boolean saveEntities, boolean saveTileEntities, boolean saveContainers) { + private byte[] createWDLPacket(int saveRadius, boolean cacheChunks, boolean saveEntities, boolean saveTileEntities, boolean saveContainers) { ByteArrayDataOutput output = ByteStreams.newDataOutput(); output.writeInt(1); - output.writeBoolean(globalIsEnabled); - output.writeInt(saveRadius); - output.writeBoolean(cacheChunks && globalIsEnabled); - output.writeBoolean(saveEntities && globalIsEnabled); - output.writeBoolean(saveTileEntities && globalIsEnabled); - output.writeBoolean(saveContainers && saveTileEntities && globalIsEnabled); + output.writeBoolean(false); + output.writeInt(0); + output.writeBoolean(false && false); + output.writeBoolean(false && false); + output.writeBoolean(false && false); + output.writeBoolean(false && false && false); return output.toByteArray(); } diff --git a/src/main/java/eu/univento/core/listeners/SpectatorEvents.java b/src/main/java/eu/univento/core/listeners/SpectatorEvents.java new file mode 100644 index 0000000..6ff9576 --- /dev/null +++ b/src/main/java/eu/univento/core/listeners/SpectatorEvents.java @@ -0,0 +1,90 @@ +package eu.univento.core.listeners; + +import eu.univento.core.api.player.CustomPlayer; +import eu.univento.core.api.player.SpectateManager; +import eu.univento.core.api.player.Spectator; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.meta.SkullMeta; + +/** + * @author joethei + * @version 0.1 + * created at 19:41 on 17.07.2016. + */ +public class SpectatorEvents implements Listener{ + + @EventHandler + public void onInteract(PlayerInteractEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + if(e.getAction() == Action.RIGHT_CLICK_BLOCK || e.getAction() == Action.RIGHT_CLICK_AIR) { + if(SpectateManager.contains(p)) { + Spectator spectator = SpectateManager.get(p); + assert spectator != null; + if(e.getItem().getType() == Material.COMPASS) { + spectator.openPlayerListInventory(); + } + if(e.getItem().getType() == Material.BED) { + //TODO: add actual connect to optimal lobby server method call. + p.connectToServer("Lobby01"); + } + if(e.getItem().getType() == Material.PAPER) { + //TODO: add actual connect to next optimal server method call. + p.connectToServer("Lobby01"); + } + } + } + } + + @EventHandler + public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + if(SpectateManager.contains(p)) { + if(e.getRightClicked() instanceof Player) { + CustomPlayer player = CustomPlayer.getPlayer((Player) e.getRightClicked()); + Spectator spectator = SpectateManager.get(p); + assert spectator != null; + spectator.spectate(player); + } + } + } + + @EventHandler + public void onInventoryClick(InventoryClickEvent e) { + CustomPlayer p = CustomPlayer.getPlayer((Player) e.getWhoClicked()); + if(SpectateManager.contains(p)) { + if (e.getInventory().getName().equals(p.getMessage("Game.Menu.SpectateMenu"))) { + if(e.getCurrentItem().getType() == Material.SKULL_ITEM) { + SkullMeta meta = (SkullMeta) e.getCurrentItem().getItemMeta(); + CustomPlayer player = CustomPlayer.getPlayer(meta.getOwner()); + assert player != null; + Spectator spectator = SpectateManager.get(p); + assert spectator != null; + if(player.isOnline()) { + p.closeInventory(); + spectator.spectate(player); + }else{ + p.sendMessage(p.getMessage("Not_online")); + } + } + } + } + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + if(SpectateManager.contains(p)) { + Spectator spectator = SpectateManager.get(p); + assert spectator != null; + spectator.remove(); + } + } +} \ No newline at end of file diff --git a/src/main/java/eu/univento/core/listeners/WeaponEvents.java b/src/main/java/eu/univento/core/listeners/WeaponEvents.java new file mode 100644 index 0000000..5ed2d8a --- /dev/null +++ b/src/main/java/eu/univento/core/listeners/WeaponEvents.java @@ -0,0 +1,39 @@ +package eu.univento.core.listeners; + +import eu.univento.core.api.customitems.swords.CustomSwordManager; +import eu.univento.core.api.customitems.swords.CustomSword; +import eu.univento.core.api.player.CustomPlayer; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +/** + * @author joethei + * @version 0.1 + * Created at 20:54 on 12.07.2016. + */ +public class WeaponEvents implements Listener { + + @EventHandler + public void onInteract(PlayerInteractEvent e) { + CustomPlayer p = CustomPlayer.getPlayer(e.getPlayer()); + if (CustomSwordManager.valueOf(e.getItem()) != null) { + CustomSword sword = CustomSwordManager.valueOf(e.getItem()); + assert sword != null; + if(e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) { + sword.primaryAttack(); + } + if(e.getAction() == Action.LEFT_CLICK_AIR ||e.getAction() == Action.LEFT_CLICK_BLOCK) { + sword.secondaryAttack(); + } + if(e.getAction() == Action.RIGHT_CLICK_BLOCK || e.getAction() == Action.RIGHT_CLICK_AIR) { + if(p.isSneaking()) sword.sneakingAttack(); + } + if(e.getAction() == Action.LEFT_CLICK_BLOCK || e.getAction() == Action.LEFT_CLICK_AIR) { + if(p.isSneaking()) sword.sneakingAttack(); + } + + } + } +} \ No newline at end of file diff --git a/src/main/resources/language_de.properties b/src/main/resources/language_de.properties index 7164316..389f41a 100644 --- a/src/main/resources/language_de.properties +++ b/src/main/resources/language_de.properties @@ -1,31 +1,40 @@ -Prefix = §6univento §8» -Tab_Prefix = §8• §6U N I V E N T O §8• -Unknown_error = §cEs ist ein unbekannter Fehler aufgetreten -No_perms = §cDu hast keine Berechtigung diesen Befehl auszuführen -Error = §cFehler: -Not_online = §7Der angegebene Spieler ist §cnicht §7 online -Kick_restart = §cDer Server wurde neu gestartet -Kick_full = §cDieser Server ist bereits voll -Command_no_found = §cDieser Befehl konnte nicht gefunden werden +Pack.failed_download = Das Pack konnte nicht geladen werden +Pack.declined = Du hast das Pack abgelehnt, du wirst nicht das volle Spielerlebnis erhalten -Core.fix_own = §7Du wurdest §egefixt +System.unknown_error = Es ist ein unbekannter Fehler aufgetreten +System.critical_error = Es ist leider ein kritischer Fehler aufgetreten -Lobby.Item.Navigator = §eNavigator -Lobby.Item.LobbySwitcher = Lobby Wechsler -Lobby.Item.Adventure = §eAbenteuermodus -Lobby.Item.FunChest = FunChest -Lobby.Item.Profile = §eDein Profil -Lobby.Item.Youtuber = §5Youtuber Menü -Lobby.Item.YT.Forcefield = §cSchutzschild -Lobby.Item.YT.Nick.on = Nickname ist an -Lobby.Item.YT.Nick.off = Nickname ist aus -Lobby.Item.YT.SilentLobby = Ruhige Lobby -Lobby.Item.YT.Extras = Extras -Lobby.Item.YT.Back = Zurück +Server.restart = Der Server wurde neugestartet +Server.stop = Der Server wurde ausgeschaltet +Server.reconnect = Bitte verbinde dich neu +Server.full = Dieser Server ist bereits voll +Server.ip = IP: play.univento.eu +Server.ts_ip = TeamSpeak IP: ts.univento.eu +Server.board_ip = Foren Adresse: forum.univento.eu -Lobby.Menu.Nav.Spawn = Spawn -Lobby.Menu.Nav.Strive = Strive -Lobby.Menu.Nav.Hustle = Hustle -Lobby.Menu.Nav.Build = Bau-Server +Command.prefix = univento.eu Default Command Prefix +Command.command_not_found = Dieser Befehl konnte nicht gefunden werden +Command.not_online = Der Spieler $player ist nicht online +Command.no_perms = Um diesen Befehl zu benutzen hast du keine Rechte -Hack.WorldDownloader = WorldDownloader wurde erkannt. \ No newline at end of file +Command.Build.usage = Nutze /build +Command.Build.toogle_on = Du hast den Build Modus aktiviert +Command.Build.toogle_off = Du hast den Build Modus deaktiviert + +Command.TS.usage = Nutze /ts +Command.TS.already_verified = Du wurdest bereits verifiziert +Command.TS.not_online = Du bist nicht mit dem TeamSpeak Server verbunden +Command.TS.verified = Du wurdest verifiziert + +Command.Fix.usage = Nutze /fix +Command.Fix.own = Du hast dich selbst gefixt +Command.Fix.other = Du hast $player gefixt +Command.Fix.by_other = Du wurdest von $player gefixt + +Shop.Lobby.Main = Lobby Shop +Shop.Game.Maya.Main = Maya Game Shop + +Lobby.Menu.Profile = Dein Profil +Lobby.Menu.other_Profile = Profil von $player +Lobby.Menu.Settings = Einstellungen +Lobby.Menu.Language = Sprache einstellen \ No newline at end of file