- added custom item creation and event system

- added the ability to create new shop entitys
 - created some new GUI and UI API methods
This commit is contained in:
Johannes Theiner 2016-07-28 20:17:25 +02:00
parent c99b1e0a01
commit c8b19c1c98
123 changed files with 2348 additions and 1400 deletions

View File

@ -6,22 +6,21 @@
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/src/test/java" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.spigotmc:spigot-api:1.10-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-lang:commons-lang:2.6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: junit:junit:4.10" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.hamcrest:hamcrest-core:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.avaje:ebean:2.8.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.persistence:persistence-api:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.yaml:snakeyaml:1.15" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.md-5:bungeecord-chat:1.9-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.bukkit:craftbukkit:1.10-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.spigotmc:spigot-api:1.10.2-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: commons-lang:commons-lang:2.6" level="project" />
<orderEntry type="library" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" name="Maven: junit:junit:4.10" level="project" />
<orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:1.1" level="project" />
<orderEntry type="library" name="Maven: org.avaje:ebean:2.8.1" level="project" />
<orderEntry type="library" name="Maven: javax.persistence:persistence-api:1.0" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.15" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.md-5:bungeecord-chat:1.10-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: org.bukkit:bukkit:1.10.2-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: org.bukkit:craftbukkit:1.10.2-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongo-java-driver:3.2.2" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongodb-driver-async:3.2.2" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongodb-driver-core:3.2.2" level="project" />

10
pom.xml
View File

@ -61,14 +61,18 @@
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.10-R0.1-SNAPSHOT</version>
<version>1.10.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.10.2-R0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.10-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<version>1.10.2-R0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>

View File

@ -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();

View File

@ -5,6 +5,6 @@ package eu.univento.cloud.client;
* @version 0.1
* created on 08.07.2016
*/
public class CloudManager {
class CloudManager {
}

View File

@ -19,6 +19,6 @@ public class CloudMessenger {
HACK,
CMD,
AD,
ERROR;
ERROR
}
}

View File

@ -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
//TODO: rewrite database operations from sync MongoDB to async MongoDB
/**
* plugin instance
*/
private static Core instance;
/**
* @return plugin instance
*/
public static Core getInstance() {
return instance;
}
/**
* plugin instance
*/
private static Core 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;
}
/*
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;
/**
* @return plugin instance
*/
public static Core getInstance() {
return instance;
}
/*
private static AsyncMongoDB asyncMongoDB;
public static AsyncMongoDB getAsyncMongoDB() {
return asyncMongoDB;
private ArrayList<String> 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<CustomPlayer> timeout = new ArrayList<>();
public static List<CustomPlayer> 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<CustomPlayer> getOnlinePlayers() {
ArrayList<CustomPlayer> list = new ArrayList<>();
for(Player players : Bukkit.getOnlinePlayers()) {
public static Collection<CustomPlayer> getOnlinePlayers() {
Collection<CustomPlayer> 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);
}
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);
@Override
public void onDisable() {
mongoDB.getClient().close();
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().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.getMessenger().unregisterIncomingPluginChannel(this);
Bukkit.getMessenger().unregisterOutgoingPluginChannel(this);
log(Level.INFO, "\n" +
this.injection.disable();
log(Level.INFO, "\n" +
"\n" +
" \n" +
" \n" +
@ -226,6 +241,6 @@ public class Core extends JavaPlugin{
" \n" +
" \n" +
"\nd");
}
}
}

View File

@ -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<CustomPlayer, Integer> 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());
}

View File

@ -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;
}
}

View File

@ -10,7 +10,7 @@ import java.util.HashMap;
public class AutoClicker implements Listener {
public static HashMap<CustomPlayer, Integer> clicks = new HashMap<>();
public static final HashMap<CustomPlayer, Integer> clicks = new HashMap<>();
@EventHandler
public void onClick(PlayerInteractEvent e) {

View File

@ -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<CustomPlayer, Long> time = new HashMap<>();
private final HashMap<CustomPlayer, Long> 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);
}

View File

@ -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<CustomPlayer> players = new ArrayList<>();
private final ArrayList<CustomPlayer> 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);
}

View File

@ -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<CustomPlayer, Long> time = new HashMap<>();
private final HashMap<CustomPlayer, Long> 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());

View File

@ -16,7 +16,7 @@ import java.util.UUID;
public class KillAura implements Listener{
public static HashMap<Player, FakePlayer> players = new HashMap<>();
public static final HashMap<Player, FakePlayer> players = new HashMap<>();
@EventHandler
public void onEntityDamage(EntityDamageByEntityEvent e) {

View File

@ -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<CustomPlayer, Long> last = new LinkedHashMap<>();
private LinkedHashMap<CustomPlayer, Integer> blocks = new LinkedHashMap<>();
private final LinkedHashMap<CustomPlayer, Long> last = new LinkedHashMap<>();
private final LinkedHashMap<CustomPlayer, Integer> 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);

View File

@ -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<CustomPlayer> a = new ArrayList<>();
private ArrayList<CustomPlayer> b = new ArrayList<>();
private final ArrayList<CustomPlayer> a = new ArrayList<>();
private final ArrayList<CustomPlayer> 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);

View File

@ -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<Player, Integer> killAura = new HashMap<>();
private HashMap<Player, Integer> count = new HashMap<>();
private HashMap<Player, Long> inventory = new HashMap<>();
private ArrayList<Player> swing = new ArrayList<>();
class PacketHandler extends ChannelDuplexHandler {
private final Player player;
private final HashMap<Player, Integer> killAura = new HashMap<>();
private final HashMap<Player, Integer> count = new HashMap<>();
private final HashMap<Player, Long> inventory = new HashMap<>();
private final ArrayList<Player> 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);
}

View File

@ -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) {

View File

@ -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<Packet<?>>() {
this.channel.pipeline().addAfter("decoder", "PacketInjector", new MessageToMessageDecoder<Packet<?>>() {
protected void decode(final ChannelHandlerContext arg0, final Packet<?> packet, final List<Object> arg2) throws Exception {
arg2.add(packet);
PacketReader.this.readPackets(packet);

View File

@ -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 {

View File

@ -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);
}
}

View File

@ -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 <P> main class
*/
public abstract class AutoCommand<P extends JavaPlugin> extends Command {
@ -28,8 +28,8 @@ public abstract class AutoCommand<P extends JavaPlugin> 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);

View File

@ -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<UUID, Integer> ticksLeft = new HashMap<UUID, Integer>();
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);
}
}

View File

@ -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");
}
/**

View File

@ -12,10 +12,9 @@ import java.util.List;
public class Hologram {
private List<EntityArmorStand> entitylist = new ArrayList<>();
private String[] text;
private Location location;
private double DISTANCE = 0.25D;
private final List<EntityArmorStand> 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;
}

View File

@ -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);
}
}
}

View File

@ -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);
}
/**

View File

@ -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 {
}

View File

@ -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 {
}

View File

@ -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();
}
}

View File

@ -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());
}
}

View File

@ -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<CustomSword> 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);
}
}

View File

@ -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;
}

View File

@ -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<ResultSet> 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));
});
}

View File

@ -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)

View File

@ -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() {

View File

@ -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;
}

View File

@ -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;
}
*/
}

View File

@ -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;
}
}

View File

@ -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<UUID, Integer> 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);
}
}

View File

@ -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) {

View File

@ -384,8 +384,8 @@ public enum ParticleEffect {
*/
MOB_APPEARANCE("mobappearance", 41, 8);
private static final Map<String, ParticleEffect> NAME_MAP = new HashMap<String, ParticleEffect>();
private static final Map<Integer, ParticleEffect> ID_MAP = new HashMap<Integer, ParticleEffect>();
private static final Map<String, ParticleEffect> NAME_MAP = new HashMap<>();
private static final Map<Integer, ParticleEffect> 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<Player> players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException {
private void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List<Player> 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<Player> players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException {
private void display(Vector direction, float speed, Location center, List<Player> 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<Player> players) throws ParticleVersionException, ParticleColorException {
private void display(ParticleColor color, Location center, List<Player> 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<Player> players) throws ParticleVersionException, ParticleDataException {
private void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List<Player> 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<Player> players) throws ParticleVersionException, ParticleDataException {
private void display(ParticleData data, Vector direction, float speed, Location center, List<Player> 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
*
@ -1297,10 +1297,9 @@ 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);
}
}
@ -1551,11 +1550,10 @@ 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);
}
}
@ -1573,11 +1571,10 @@ 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);
}
}

View File

@ -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<Location> 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));
}
}
}

View File

@ -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<String> 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();
}
}
}

View File

@ -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);

View File

@ -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;
}
}

View File

@ -27,8 +27,8 @@ public class MoveEventFilter implements Listener {
public World world;
}
private Server mServer;
private WeakHashMap<Player, BlockPosition> mLastPosition = new WeakHashMap<>();
private final Server mServer;
private final WeakHashMap<Player, BlockPosition> mLastPosition = new WeakHashMap<>();
public MoveEventFilter(Server pServer) {
mServer = pServer;

View File

@ -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();
}

View File

@ -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) {

View File

@ -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<CustomPlayer> players = new LinkedList<>();
public static List<CustomPlayer> 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();
}
}

View File

@ -11,10 +11,10 @@ import java.util.ArrayList;
*/
public class Team {
private ArrayList<CustomPlayer> players = new ArrayList<>();
private String name;
private String prefix;
private org.bukkit.scoreboard.Team team;
private final ArrayList<CustomPlayer> 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;

View File

@ -8,9 +8,9 @@ import java.util.ArrayList;
* @author joethei
* @version 0.1
*/
public class TeamManager {
class TeamManager {
private static ArrayList<Team> teams = new ArrayList<>();
private static final ArrayList<Team> teams = new ArrayList<>();
public static ArrayList<Team> getTeams() {
return teams;

View File

@ -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<AnvilSlot, ItemStack> items = new HashMap<AnvilSlot, ItemStack>();
private HashMap<AnvilSlot, ItemStack> 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;

View File

@ -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);

View File

@ -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();

View File

@ -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()) {

View File

@ -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;
}

View File

@ -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;
}
}

View File

@ -12,11 +12,11 @@ import java.util.Optional;
* @author leNic
* @version 1.0
*/
public class Pagifier<T> {
class Pagifier<T> {
// Properties
private int pageSize;
private final int pageSize;
// List of pages
private List<List<T>> pages;
private final List<List<T>> pages;
// Constructor
public Pagifier(int pageSize){
this.pageSize = pageSize;

View File

@ -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<ItemStack> items = new ArrayList<>();
private final Inventory inv;
private final ArrayList<ItemStack> 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){

View File

@ -8,13 +8,13 @@ import java.util.ResourceBundle;
public class Language {
private ResourceBundle translation;
private final ResourceBundle translation;
public Language(String language) {
Map<String, Locale> 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));
}

View File

@ -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();

View File

@ -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";
}
}

View File

@ -19,7 +19,7 @@ public class Cuboid implements Cloneable, ConfigurationSerializable, Iterable<Bl
private String worldName;
private final Vector minimumPoint, maximumPoint;
public Cuboid(Cuboid cuboid) {
private Cuboid(Cuboid cuboid) {
this(cuboid.worldName, cuboid.minimumPoint.getX(), cuboid.minimumPoint.getY(), cuboid.minimumPoint.getZ(), cuboid.maximumPoint.getX(), cuboid.maximumPoint.getY(), cuboid.maximumPoint.getZ());
}
@ -50,7 +50,7 @@ public class Cuboid implements Cloneable, ConfigurationSerializable, Iterable<Bl
}
}
public Cuboid(String worldName, double x1, double y1, double z1, double x2, double y2, double z2) {
private Cuboid(String worldName, double x1, double y1, double z1, double x2, double y2, double z2) {
if (worldName == null || Bukkit.getServer().getWorld(worldName) == null)
throw new NullPointerException("One/both of the worlds is/are null!");
this.worldName = worldName;
@ -124,7 +124,7 @@ public class Cuboid implements Cloneable, ConfigurationSerializable, Iterable<Bl
return (this.getUpperX() - this.getLowerX() + 1) * (this.getUpperY() - this.getLowerY() + 1) * (this.getUpperZ() - this.getLowerZ() + 1);
}
public World getWorld() {
private World getWorld() {
World world = Bukkit.getServer().getWorld(this.worldName);
if (world == null) throw new NullPointerException("World '" + this.worldName + "' is not loaded.");
return world;

View File

@ -8,10 +8,10 @@ import org.bukkit.Material;
*/
public class Map {
private String name;
private String builder;
private Material item;
private String download;
private final String name;
private final String builder;
private final Material item;
private final String download;
public Map(String name, String builder, Material item, String download) {
this.name = name;

View File

@ -1,6 +1,6 @@
package eu.univento.core.api.map;
import eu.univento.core.api.server.Game;
import eu.univento.core.api.server.ServerType;
import org.bukkit.Material;
import java.util.ArrayList;
@ -9,10 +9,10 @@ import java.util.ArrayList;
* @author joethei
* @version 0.1
*/
public class MapDatabase {
class MapDatabase {
//TODO: add real map database
public static ArrayList<Map> getAllMaps(Game game) {
public static ArrayList<Map> getAllMaps(ServerType serverType) {
ArrayList<Map> maps = new ArrayList<>();
maps.add(new Map("Map1", "TeamVento", Material.GRASS, "http://creppy.univento.eu/maps/Strive/Map1"));

View File

@ -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 {

View File

@ -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<CustomPlayer> votes1 = new ArrayList<>();
private ArrayList<CustomPlayer> votes2 = new ArrayList<>();
private ArrayList<CustomPlayer> votes3 = new ArrayList<>();
private final String invTitle;
private final ArrayList<CustomPlayer> votes1 = new ArrayList<>();
private final ArrayList<CustomPlayer> votes2 = new ArrayList<>();
private final ArrayList<CustomPlayer> votes3 = new ArrayList<>();
private Map forcedMap;
private ArrayList<Map> allMaps = new ArrayList<>();
private final ArrayList<Map> 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);

View File

@ -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);

View File

@ -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<? extends EntityInsentient> nmsClass;
private Class<? extends EntityInsentient> customClass;
private final String name;
private final int id;
private final EntityType type;
private final Class<? extends EntityInsentient> nmsClass;
private final Class<? extends EntityInsentient> customClass;
PetType(String name, int id, EntityType type, Class<? extends EntityInsentient> nmsClass, Class<? extends EntityInsentient> 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<? extends EntityInsentient> getNmsClass() {
private Class<? extends EntityInsentient> getNmsClass() {
return nmsClass;
}

View File

@ -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

View File

@ -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;
}
}

View File

@ -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<String, CustomPlayer> PLAYERS = new HashMap<>();
private static final HashMap<UUID, CustomPlayer> PLAYERS = new HashMap<>();
private final Player PLAYER;
private String customPrefix;
private String customSuffix;
private String customColor;
private String nickname;
private boolean openInventory;
private MongoCollection<Document> playerCollection;
private MongoCollection<Document> friendCollection;
private MongoCollection<Document> onlinePlayerCollection;
private final MongoCollection<Document> playerCollection;
private final MongoCollection<Document> friendCollection;
private final MongoCollection<Document> onlinePlayerCollection;
private final MongoCollection<Document> 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<String, Object> 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<Document> 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<ShopItem, Boolean> map = getBoughtItems();
map.put(item, false);
setBoughtItems(map);
}
public Map<ShopItem, Boolean> getBoughtItems() {
Map<ShopItem, Boolean> map = new HashMap<>();
for (Map.Entry<String, Object> entry : getMapFromDatabase("bought").entrySet())
map.put(ShopItem.valueOf(String.valueOf(entry.getKey())), Boolean.valueOf(String.valueOf(entry.getValue())));
return map;
}
private void setBoughtItems(Map<ShopItem, Boolean> map) {
Map<String, Boolean> items = new HashMap<>();
for (Map.Entry<ShopItem, Boolean> 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<String> getFoundSecrets() {
private ArrayList<String> getFoundSecrets() {
return getArrayListFromDatabase("foundSecrets");
}
@ -346,33 +362,35 @@ public class CustomPlayer extends CraftPlayer {
return getRank().getValue() >= rank.getValue();
}
public ArrayList<UUID> getFriends() {
public Collection<FriendObject> getFriends() {
FindIterable<Document> cursor = friendCollection.find(new Document("uuid", getUniqueId().toString()));
cursor.cursorType(CursorType.NonTailable);
Document doc = cursor.first();
if (doc == null) return null;
return (ArrayList<UUID>) doc.get("friends");
}
LinkedList<UUID> list = (LinkedList<UUID>) doc.get("friends");
private void setFriends(ArrayList<UUID> 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<UUID> 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<Document> 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);
}
}

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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;

View File

@ -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;

View File

@ -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<Spectator> 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;
}
}

View File

@ -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<CustomPlayer> 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<CustomPlayer>
*/
public static ArrayList<CustomPlayer> getSpectators() {
return spectators;
}
/**
* checks if players is spectator
* @param p CustomPlayer
* @return true/false
*/
public static boolean is(CustomPlayer p) {
return spectators.contains(p);
}
}

View File

@ -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;
}
}

View File

@ -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
}

View File

@ -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() {

View File

@ -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;

View File

@ -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();
}
}

View File

@ -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;
}

View File

@ -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() {

View File

@ -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);
}

View File

@ -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() {

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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<ShopItem> 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);
}
}

View File

@ -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());
}
}
}

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -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<CustomPlayer> players = new ArrayList<>();
private ArrayList<Location> locations = new ArrayList<>();
@ -92,7 +91,6 @@ public class Camera {
}
public Camera(String name) {
this.name = name;
load();
}

View File

@ -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()

View File

@ -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<UUID, CachedProfile> cache = new HashMap<>();
private static final HashMap<UUID, CachedProfile> 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<Object> args = new ArrayList<Object>();
List<Object> 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;
}
}
}

View File

@ -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);
}

View File

@ -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<Channel> 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<String> 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<String, PacketHandler> handlerList = new HashMap<String, PacketHandler>();
private Listener listener;
private final HashMap<String, Channel> playerChannel = new HashMap<String, Channel>();
private final List<Channel> globalChannel = new ArrayList<Channel>();
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<Channel> last = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
NettyInjection.this.injectChannel(channel);
}
};
ChannelInitializer<Channel> first = new ChannelInitializer<Channel>() {
@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<Object> channelFuture = (List<Object>) 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);
}
}
}

Some files were not shown because too many files have changed in this diff Show More