From 24f8d0dcecc5c56078859246a0e2f1c202bc5a1f Mon Sep 17 00:00:00 2001 From: joethei Date: Fri, 7 Apr 2017 17:10:36 +0200 Subject: [PATCH] ~ Async Database Handling --- .gitlab/issue_templates/Bug.md | 3 + .gitlab/issue_templates/Feature.md | 0 Commons.iml | 39 +- pom.xml | 36 +- .../java/eu/univento/commons/Commons.java | 7 +- .../commons/database/AsyncMongoDB.java | 28 - .../univento/commons/database/AsyncMySQL.java | 41 -- .../commons/database/DatabaseManager.java | 14 - .../eu/univento/commons/database/MongoDB.java | 56 +- .../eu/univento/commons/database/MySQL.java | 73 +- .../eu/univento/commons/database/Redis.java | 26 +- .../commons/player/DatabasePlayer.java | 656 ++++++++++-------- .../univento/commons/player/MongoPlayer.java | 26 - .../univento/commons/player/ban/BanData.java | 9 +- .../commons/player/hacks/HackData.java | 196 ------ .../commons/player/kick/KickData.java | 8 +- .../commons/player/language/Language.java | 49 -- .../commons/player/language/Languages.java | 30 - .../commons/player/language/Translation.java | 32 - .../commons/player/mute/MuteData.java | 12 +- .../eu/univento/commons/player/rank/Rank.java | 18 +- .../player/settings/PlayerSettings.java | 163 ++--- .../commons/player/statistics/GameStat.java | 15 + .../commons/player/statistics/GameStats.java | 4 +- .../commons/player/warn/WarnData.java | 8 +- .../java/eu/univento/commons/utils/Pool.java | 117 ++++ 26 files changed, 678 insertions(+), 988 deletions(-) create mode 100644 .gitlab/issue_templates/Bug.md create mode 100644 .gitlab/issue_templates/Feature.md delete mode 100644 src/main/java/eu/univento/commons/database/AsyncMongoDB.java delete mode 100644 src/main/java/eu/univento/commons/database/AsyncMySQL.java delete mode 100644 src/main/java/eu/univento/commons/player/MongoPlayer.java delete mode 100644 src/main/java/eu/univento/commons/player/hacks/HackData.java delete mode 100644 src/main/java/eu/univento/commons/player/language/Language.java delete mode 100644 src/main/java/eu/univento/commons/player/language/Languages.java delete mode 100644 src/main/java/eu/univento/commons/player/language/Translation.java create mode 100644 src/main/java/eu/univento/commons/player/statistics/GameStat.java create mode 100644 src/main/java/eu/univento/commons/utils/Pool.java diff --git a/.gitlab/issue_templates/Bug.md b/.gitlab/issue_templates/Bug.md new file mode 100644 index 0000000..6f0f4bf --- /dev/null +++ b/.gitlab/issue_templates/Bug.md @@ -0,0 +1,3 @@ +Was hast du gemacht als der Bug aufgetreten ist ? + +Ausgabe des `/bureport` Befehls: \ No newline at end of file diff --git a/.gitlab/issue_templates/Feature.md b/.gitlab/issue_templates/Feature.md new file mode 100644 index 0000000..e69de29 diff --git a/Commons.iml b/Commons.iml index 641cdf9..5045962 100644 --- a/Commons.iml +++ b/Commons.iml @@ -12,16 +12,35 @@ - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index d13b25b..d384c65 100644 --- a/pom.xml +++ b/pom.xml @@ -58,37 +58,25 @@ lombok 1.14.8 - - - org.mongodb.morphia - morphia - 1.3.1 + io.vertx + vertx-core + 3.4.1 - com.zaxxer - HikariCP - 2.4.5 + io.vertx + vertx-redis-client + 3.4.1 - com.zaxxer - SansOrm - 1.0 + io.vertx + vertx-mysql-postgresql-client + 3.4.1 - javax.persistence - persistence-api - 1.0.2 - - - redis.clients - jedis - 2.9.0 + io.vertx + vertx-mongo-client + 3.4.1 com.google.code.gson diff --git a/src/main/java/eu/univento/commons/Commons.java b/src/main/java/eu/univento/commons/Commons.java index 2f620d5..9be0696 100644 --- a/src/main/java/eu/univento/commons/Commons.java +++ b/src/main/java/eu/univento/commons/Commons.java @@ -3,8 +3,8 @@ package eu.univento.commons; import eu.univento.commons.configuration.ConfigurationHandler; import eu.univento.commons.database.DatabaseManager; import eu.univento.commons.logging.LoggingHandler; -import eu.univento.commons.player.language.Languages; import eu.univento.commons.security.SecurityHandler; +import io.vertx.core.Vertx; import lombok.Getter; /** @@ -21,6 +21,7 @@ public class Commons { private ConfigurationHandler configurationHandler; private SecurityHandler securityHandler; private LoggingHandler loggingHandler; + private Vertx vertx; public Commons() { commons = this; @@ -28,11 +29,11 @@ public class Commons { databaseManager = new DatabaseManager(this); securityHandler = new SecurityHandler(this); loggingHandler = new LoggingHandler(); - Languages.init(); + vertx = Vertx.vertx(); } public void shutdown() { - getDatabaseManager().closeConnections(); + vertx.close(); } public static Commons getCommons() { diff --git a/src/main/java/eu/univento/commons/database/AsyncMongoDB.java b/src/main/java/eu/univento/commons/database/AsyncMongoDB.java deleted file mode 100644 index ccd808b..0000000 --- a/src/main/java/eu/univento/commons/database/AsyncMongoDB.java +++ /dev/null @@ -1,28 +0,0 @@ -package eu.univento.commons.database; - -import com.mongodb.client.MongoDatabase; -import lombok.Getter; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.function.Consumer; - -/** - * @author joethei - * @version 1.0 - */ -public class AsyncMongoDB { - - @Getter private ExecutorService executor; - @Getter private MongoDB mongoDB; - - public AsyncMongoDB(String host, int port, String user, String password, String database) { - mongoDB = new MongoDB(host, port, user, password, database); - executor = Executors.newCachedThreadPool(); - } - - public void getDatabase(Consumer consumer) { - consumer.accept(mongoDB.getDatabase()); - } - -} \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/database/AsyncMySQL.java b/src/main/java/eu/univento/commons/database/AsyncMySQL.java deleted file mode 100644 index bc6164f..0000000 --- a/src/main/java/eu/univento/commons/database/AsyncMySQL.java +++ /dev/null @@ -1,41 +0,0 @@ -package eu.univento.commons.database; - -import lombok.Getter; - -import java.sql.ResultSet; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.function.Consumer; - -/** - * @author joethei - * @version 1.0 - */ -public class AsyncMySQL { - - private ExecutorService executor; - @Getter - private MySQL mySQL; - - public AsyncMySQL(String host, String port, String user, String password, String database) { - try { - mySQL = new MySQL(host, port, user, password, database); - executor = Executors.newCachedThreadPool(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void update(String update) { - executor.execute(() -> mySQL.update(update)); - } - - public void query(String query, Consumer consumer) { - executor.execute(() -> { - ResultSet result; - result = mySQL.query(query); - ResultSet finalResult = result; - consumer.accept(finalResult); - }); - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/database/DatabaseManager.java b/src/main/java/eu/univento/commons/database/DatabaseManager.java index 92d3c76..fe307f2 100644 --- a/src/main/java/eu/univento/commons/database/DatabaseManager.java +++ b/src/main/java/eu/univento/commons/database/DatabaseManager.java @@ -15,28 +15,14 @@ public class DatabaseManager { //TODO: add board sql back, when forum is online. private MongoDB mongoDB; - private AsyncMongoDB asyncMongoDB; private MySQL mySQL; - private AsyncMySQL asyncMySQL; - private AsyncMySQL boardSQL; private Redis redis; public DatabaseManager(Commons commons) { ConfigurationHandler config = commons.getConfigurationHandler(); mongoDB = new MongoDB(config.getString("MongoDB.Host"), config.getInteger("MongoDB.Port"), config.getString("MongoDB.Username"), config.getString("MongoDB.Password"), config.getString("MongoDB.Database")); - asyncMongoDB = new AsyncMongoDB(config.getString("MongoDB.Host"), config.getInteger("MongoDB.Port"), config.getString("MongoDB.Username"), config.getString("MongoDB.Password"), config.getString("MongoDB.Database")); mySQL = new MySQL(config.getString("MySQL.Host"), config.getString("MySQL.Port"), config.getString("MySQL.Database"), config.getString("MySQL.Username"), config.getString("MySQL.Password")); - asyncMySQL = new AsyncMySQL(config.getString("MySQL.Host"), config.getString("MySQL.Port"), config.getString("MySQL.Database"), config.getString("MySQL.Username"), config.getString("MySQL.Password")); - //boardSQL = new AsyncMySQL(config.getString("BoardSQL.Host"), config.getString("BoardSQL.Port"), config.getString("BoardSQL.Database"), config.getString("BoardSQL.Username"), config.getString("BoardSQL.Password")); redis = new Redis(config.getString("Redis.Hostname"), config.getInteger("Redis.Port"), config.getString("Redis.Password")); } - public void closeConnections() { - mongoDB.closeConnection(); - asyncMongoDB.getMongoDB().closeConnection(); - mySQL.close(); - asyncMySQL.getMySQL().close(); - //boardSQL.getMySQL().close(); - redis.close(); - } } \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/database/MongoDB.java b/src/main/java/eu/univento/commons/database/MongoDB.java index b4300c1..79f7b4f 100644 --- a/src/main/java/eu/univento/commons/database/MongoDB.java +++ b/src/main/java/eu/univento/commons/database/MongoDB.java @@ -1,14 +1,9 @@ package eu.univento.commons.database; -import com.mongodb.MongoClient; -import com.mongodb.MongoCredential; -import com.mongodb.ServerAddress; -import com.mongodb.client.MongoDatabase; +import eu.univento.commons.Commons; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.mongo.MongoClient; import lombok.Getter; -import org.mongodb.morphia.Datastore; -import org.mongodb.morphia.Morphia; - -import java.util.Collections; /** * @author joethei @@ -16,50 +11,11 @@ import java.util.Collections; */ public class MongoDB { - private final MongoClient client; - @Getter private final Datastore datastore; - private MongoDatabase database; - - private final String host; - private final int port; - private final String username; - private final String password; - private final String databaseName; + @Getter private MongoClient client; public MongoDB(String host, int port, String username, String password, String databaseName) { - this.host = host; - this.port = port; - this.username = username; - this.password = password; - this.databaseName = databaseName; - - MongoCredential credential = MongoCredential.createCredential(username, databaseName, password.toCharArray()); - client = new MongoClient(new ServerAddress(host, port), Collections.singletonList(credential)); - - Morphia morphia = new Morphia(); - morphia.mapPackage("eu.univento.commons.player"); - - datastore = morphia.createDatastore(client, "univento"); - datastore.ensureIndexes(); + client = MongoClient.createShared(Commons.getCommons().getVertx(), + new JsonObject().put("host", host).put("port", port).put("username", username).put("password", password).put("authSource", databaseName)); } - private MongoClient getClient() { - if(client == null) - new MongoDB(host, port, username, password, databaseName); - return client; - } - - public MongoDatabase getDatabase() { - if(database == null) - database = getClient().getDatabase(databaseName); - return database; - } - public void setDatabase(String database) { - this.database = getClient().getDatabase(database); - } - - void closeConnection() { - if(client != null) - client.close(); - } } \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/database/MySQL.java b/src/main/java/eu/univento/commons/database/MySQL.java index 5474a0d..815aaca 100644 --- a/src/main/java/eu/univento/commons/database/MySQL.java +++ b/src/main/java/eu/univento/commons/database/MySQL.java @@ -1,12 +1,10 @@ package eu.univento.commons.database; -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import eu.univento.commons.Commons; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.asyncsql.AsyncSQLClient; +import io.vertx.ext.asyncsql.MySQLClient; +import lombok.Getter; /** * @author joethei @@ -14,65 +12,10 @@ import java.sql.SQLException; */ public class MySQL { - private final HikariDataSource dataSource; + @Getter private AsyncSQLClient client; public MySQL(String hostname, String port, String database, String username, String password) { - HikariConfig config = new HikariConfig(); - config.setMaximumPoolSize(10); - config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"); - config.addDataSourceProperty("serverName", hostname); - config.addDataSourceProperty("port", port); - config.addDataSourceProperty("databaseName", database); - config.addDataSourceProperty("user", username); - config.addDataSourceProperty("password", password); - config.addDataSourceProperty("cachePrepStmts", "true"); - config.addDataSourceProperty("prepStmtCacheSize", "250"); - config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); - - dataSource = new HikariDataSource(config); - } - - public void close() { - try { - dataSource.getConnection().close(); - dataSource.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - 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; + client = MySQLClient.createShared(Commons.getCommons().getVertx(), + new JsonObject().put("host", hostname).put("port", port).put("username", username).put("password", password).put("database", database)); } } \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/database/Redis.java b/src/main/java/eu/univento/commons/database/Redis.java index 2d23d01..0c4b2a9 100644 --- a/src/main/java/eu/univento/commons/database/Redis.java +++ b/src/main/java/eu/univento/commons/database/Redis.java @@ -5,9 +5,10 @@ package eu.univento.commons.database; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; +import eu.univento.commons.Commons; +import io.vertx.redis.RedisClient; +import io.vertx.redis.RedisOptions; +import lombok.Getter; /** * @author joethei @@ -15,22 +16,9 @@ import redis.clients.jedis.JedisPoolConfig; */ public class Redis { - private JedisPool jedisPool; + @Getter private RedisClient client; - public Redis(String hostname, int port, String password) { - JedisPoolConfig poolConfig = new JedisPoolConfig(); - poolConfig.setMinIdle(8); - poolConfig.setMaxTotal(32); - - jedisPool = new JedisPool(poolConfig, hostname, port, 5000, password); - } - - public Jedis getJedis() { - return jedisPool.getResource(); - } - - public void close() { - jedisPool.close(); - jedisPool.destroy(); + public Redis(String host, int port, String password) { + client = RedisClient.create(Commons.getCommons().getVertx(), new RedisOptions().setHost(host).setPort(port).setAuth(password)); } } \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/player/DatabasePlayer.java b/src/main/java/eu/univento/commons/player/DatabasePlayer.java index 104e747..2c39736 100644 --- a/src/main/java/eu/univento/commons/player/DatabasePlayer.java +++ b/src/main/java/eu/univento/commons/player/DatabasePlayer.java @@ -1,224 +1,298 @@ package eu.univento.commons.player; -import com.mongodb.CursorType; -import com.mongodb.client.FindIterable; -import com.mongodb.client.MongoCollection; import eu.univento.commons.Commons; -import eu.univento.commons.database.MongoDB; import eu.univento.commons.player.ban.BanData; import eu.univento.commons.player.ban.BanReason; import eu.univento.commons.player.friend.FriendData; -import eu.univento.commons.player.hacks.HackData; import eu.univento.commons.player.kick.KickData; import eu.univento.commons.player.kick.KickReason; -import eu.univento.commons.player.language.Language; -import eu.univento.commons.player.language.Languages; import eu.univento.commons.player.mute.MuteData; import eu.univento.commons.player.mute.MuteReason; -import eu.univento.commons.player.profiles.Profile; import eu.univento.commons.player.rank.Group; import eu.univento.commons.player.rank.Rank; import eu.univento.commons.player.ranking.Ranking; import eu.univento.commons.player.settings.PlayerSettings; import eu.univento.commons.player.warn.WarnData; import eu.univento.commons.player.warn.WarnReason; -import lombok.Data; -import org.bson.Document; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.mongo.MongoClient; +import lombok.Getter; +import java.time.Instant; import java.util.*; +import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; /** * @author joethei - * @version 1.0 + * @version 1.5 */ -@Data +@Getter public class DatabasePlayer { private UUID uuid; private String name; - private final PlayerSettings settings; - private final HackData hackData; - private final Language language; - - private final MongoCollection playerCollection; - private final MongoCollection friendCollection; - private final MongoCollection onlinePlayerCollection; - private final MongoCollection banCollection; - private final MongoCollection warnCollection; - private final MongoCollection kickCollection; - private final MongoCollection muteCollection; - private final MongoCollection profileCollection; - - public DatabasePlayer(Commons commons, UUID uuid, String name) { + public DatabasePlayer(UUID uuid, String name) { this.uuid = uuid; this.name = name; - - MongoDB mongoDB = commons.getDatabaseManager().getMongoDB(); - playerCollection = mongoDB.getDatabase().getCollection("players"); - friendCollection = mongoDB.getDatabase().getCollection("friends"); - onlinePlayerCollection = mongoDB.getDatabase().getCollection("onlinePlayers"); - banCollection = mongoDB.getDatabase().getCollection("bans"); - warnCollection = mongoDB.getDatabase().getCollection("warns"); - kickCollection = mongoDB.getDatabase().getCollection("kicks"); - muteCollection = mongoDB.getDatabase().getCollection("mutes"); - profileCollection = mongoDB.getDatabase().getCollection("profiles"); - - settings = new PlayerSettings(this); - hackData = new HackData(this); - language = Languages.getLanguage(getSettings().getLanguage()); } - public Collection getProfiles() { - return getArrayListFromDatabase("profiles").stream().map(id -> new Profile(this, id)).collect(Collectors.toCollection(LinkedList::new)); + private PlayerSettings settings; + public PlayerSettings getSettings() { + if(settings == null) { + getSettingsFromDatabase().whenComplete((playerSettings, throwable) -> settings = playerSettings); + } + return settings; } - public MongoPlayer query() { - return Commons.getCommons().getDatabaseManager().getMongoDB().getDatastore().createQuery(MongoPlayer.class).field("uuid").equal(uuid).get(); + public CompletableFuture getSettingsFromDatabase() { + CompletableFuture future = new CompletableFuture<>(); + getObjectFromDatabase("Settings").whenComplete((entries, throwable) -> { + future.complete(new PlayerSettings(this, entries)); + }); + return future; } - public Ranking getRanking() { - return Ranking.getFromInt(getIntegerFromDatabase("ranking")); + public CompletableFuture getRanking() { + CompletableFuture future = new CompletableFuture<>(); + getObjectFromDatabase("ranking").whenComplete((entries, throwable) -> + future.complete(Ranking.valueOf(entries.getString("ranking")))); + return future; + } public void ban(BanReason reason, UUID banner, String customMessage, String proof) { - Document doc = new Document("uuid", uuid.toString()); - int i = 0; - if(getAllBans().size() > 1) { - for (BanData ban : getAllBans()) i =+ ban.getReason().getValue(); - } - Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.DAY_OF_YEAR, reason.getValue() + i); - doc.put("date", calendar.getTime()); - doc.put("reason", reason.name()); - doc.put("banner", banner.toString()); - doc.put("customMessage", customMessage); - doc.put("proof", proof); + getAllBans().whenComplete((banData, throwable) -> { + int i = 0; + if (banData.size() > 1) { + for (BanData ban : banData) { + i = +ban.getReason().getValue(); + } + } + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.DAY_OF_YEAR, reason.getValue() + i); + JsonObject obj = new JsonObject().put("uuid", uuid.toString()) + .put("date", calendar.getTime()) + .put("reason", reason.name()) + .put("banner", banner.toString()) + .put("customMessage", customMessage) + .put("proof", proof); + + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.insert("bans", obj, res -> { + if (res.failed()) { + try { + throw res.cause(); + } catch (Throwable throwable1) { + throwable1.printStackTrace(); + } + } + }); + client.close(); + }); - banCollection.insertOne(doc); } - public BanData getBan() { - FindIterable cursor = banCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - if(cursor.first() == null) return null; - Document doc = cursor.first(); - return new BanData(BanReason.valueOf(doc.getString("reason")), UUID.fromString(doc.getString("banner")), doc.getString("customMessage"), doc.getDate("date"), doc.getString("proof")); + public CompletableFuture getBan() { + CompletableFuture future = new CompletableFuture<>(); + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.findOne("bans", new JsonObject().put("uuid", uuid.toString()), null, res -> { + JsonObject result = res.result(); + BanData data = new BanData(BanReason.valueOf(result.getString("reason")), + UUID.fromString(result.getString("banner")), + result.getString("customMessage"), + result.getInstant("date"), + result.getString("proof")); + client.close(); + future.complete(data); + }); + return future; } - public boolean isBanned() { - return getBan() != null && !new Date().after(getBan().getUnbanDate()); + public CompletableFuture isBanned() { + CompletableFuture future = new CompletableFuture<>(); + getBan().whenComplete((banData, throwable) -> future.complete(banData != null && !Instant.now().isAfter(banData.getUnbanDate()))); + return future; } - public Collection getAllBans() { - FindIterable cursor = banCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - Iterator iterator = cursor.iterator(); - Collection collection = new LinkedList<>(); - while(iterator.hasNext()) { - Document doc = iterator.next(); - collection.add(new BanData(BanReason.valueOf(doc.getString("reason")), UUID.fromString(doc.getString("banner")), doc.getString("customMessage"), doc.getDate("date"), doc.getString("proof"))); - } - return collection; + public CompletableFuture> getAllBans() { + CompletableFuture> future = new CompletableFuture<>(); + Collection data = new LinkedList<>(); + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.find("bans", new JsonObject().put("uuid", uuid.toString()), res -> { + if (res.succeeded()) { + for (JsonObject json : res.result()) { + data.add(new BanData(BanReason.valueOf(json.getString("reason")), + UUID.fromString(json.getString("banner")), + json.getString("customMessage"), + json.getInstant("date"), + json.getString("proof"))); + } + client.close(); + future.complete(data); + } + }); + return future; } public void warn(WarnReason reason, String warner, String proof) { - Document doc = new Document("uuid", uuid.toString()); - doc.put("reason", reason.name()); - doc.put("warner", warner); - doc.put("date", new Date()); - doc.put("proof", proof); - - warnCollection.insertOne(doc); + JsonObject obj = new JsonObject().put("uuid", uuid.toString()).put("reason", reason.getName()).put("warner", warner).put("date", Instant.now()).put("proof", proof); + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.insert("warns", obj, res -> { + if (res.failed()) { + try { + throw res.cause(); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + } + }); + client.close(); } - public boolean isWarned() { - FindIterable cursor = warnCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - Document doc = cursor.first(); - return doc != null && !new Date().after(doc.getDate("date")); + public CompletableFuture isWarned() { + CompletableFuture future = new CompletableFuture<>(); + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.findOne("warns", new JsonObject().put("uuid", uuid.toString()), null, res -> { + if (res.succeeded()) { + JsonObject json = res.result(); + future.complete(json != null && Instant.now().isAfter(json.getInstant("date"))); + } + }); + client.close(); + return future; } - public Collection getAllWarns() { - FindIterable cursor = warnCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - Iterator iterator = cursor.iterator(); - Collection collection = new LinkedList<>(); - while(iterator.hasNext()) { - Document doc = iterator.next(); - collection.add(new WarnData(WarnReason.valueOf(doc.getString("reason")), UUID.fromString(doc.getString("warner")), doc.getDate("date"), doc.getString("proof"))); - } - return collection; + public CompletableFuture> getAllWarns() { + CompletableFuture> future = new CompletableFuture<>(); + Collection data = new LinkedList<>(); + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.find("warns", new JsonObject().put("uuid", uuid.toString()), res -> { + if (res.succeeded()) { + for (JsonObject json : res.result()) { + data.add(new WarnData(WarnReason.valueOf(json.getString("reason")), + UUID.fromString(json.getString("warner")), + json.getInstant("date"), + json.getString("proof"))); + } + client.close(); + future.complete(data); + } + }); + return future; } public void kick(UUID kicker, KickReason reason) { - Document doc = new Document("uuid", uuid.toString()); - doc.put("reason", reason.name()); - doc.put("kicker", kicker.toString()); - doc.put("date", new Date()); - - kickCollection.insertOne(doc); + JsonObject obj = new JsonObject().put("uuid", uuid.toString()).put("reason", reason.name()).put("kicker", kicker.toString()).put("date", Instant.now()); + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.insert("kicks", obj, res -> { + if (res.failed()) { + try { + throw res.cause(); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + } + }); } - public Collection getAllKicks() { - FindIterable cursor = kickCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - Iterator iterator = cursor.iterator(); - LinkedList collection = new LinkedList<>(); - while(iterator.hasNext()) { - Document doc = iterator.next(); - collection.add(new KickData(KickReason.valueOf(doc.getString("reason")), doc.getDate("date"), UUID.fromString(doc.getString("kicker")))); - } - return collection; + public CompletableFuture> getAllKicks() { + CompletableFuture> future = new CompletableFuture<>(); + Collection data = new LinkedList<>(); + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.find("kicks", new JsonObject().put("uuid", uuid.toString()), res -> { + if (res.succeeded()) { + for (JsonObject json : res.result()) { + data.add(new KickData(KickReason.valueOf(json.getString("reason")), + json.getInstant("date"), + UUID.fromString("kicker"))); + } + client.close(); + future.complete(data); + } + }); + return future; } public void mute(UUID muter, MuteReason reason) { - int i = 0; - if(getAllBans().size() > 1) { - for (MuteData mute : getAllMutes()) i =+ mute.getReason().getValue(); - } - Document doc = new Document("uuid", uuid.toString()); - Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.DAY_OF_YEAR, reason.getValue() + i); - doc.put("reason", reason.name()); - doc.put("muter", muter.toString()); - doc.put("date", calendar.getTime()); - - muteCollection.insertOne(doc); - } - - public boolean isMuted() { - FindIterable cursor = muteCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - Document doc = cursor.first(); - return doc != null && !new Date().after(doc.getDate("date")); - } - - public MuteData getMute() { - for(MuteData mute : getAllMutes()) { - if(new Date().before(mute.getDate())) { - return mute; + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + getAllMutes().whenComplete((muteData, throwable) -> { + int i = 0; + if (muteData.size() > 1) { + for (MuteData mute : muteData) i = +mute.getReason().getValue(); } - } - return null; + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.DAY_OF_YEAR, reason.getValue() + i); + JsonObject obj = new JsonObject().put("uuid", uuid.toString()) + .put("reason", reason.name()) + .put("muter", muter.toString()) + .put("date", calendar.getTime()); + client.insert("mutes", obj, res -> { + if (res.failed()) { + try { + throw res.cause(); + } catch (Throwable throwable1) { + throwable1.printStackTrace(); + } + } + }); + client.close(); + }); } - public Collection getAllMutes() { - FindIterable cursor = muteCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - Iterator iterator = cursor.iterator(); - LinkedList collection = new LinkedList<>(); - while(iterator.hasNext()) { - Document doc = iterator.next(); - collection.add(new MuteData(MuteReason.valueOf(doc.getString("reason")), UUID.fromString(doc.getString("uuid")), UUID.fromString(doc.getString("muter")), doc.getDate("date"))); - } - return collection; + public CompletableFuture isMuted() { + CompletableFuture future = new CompletableFuture<>(); + getMute().whenComplete((muteData, throwable) -> { + future.complete(muteData != null && !Instant.now().isAfter(muteData.getDate())); + }); + return future; } + public CompletableFuture getMute() { + CompletableFuture future = new CompletableFuture<>(); + getAllMutes().whenComplete((muteData, throwable) -> { + for (MuteData data : muteData) { + if (Instant.now().isBefore(data.getDate())) future.complete(data); + } + }); + return future; + } + + public CompletableFuture> getAllMutes() { + CompletableFuture> future = new CompletableFuture<>(); + Collection data = new LinkedList<>(); + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.find("mutes", new JsonObject().put("uuid", uuid.toString()), res -> { + if (res.succeeded()) { + for (JsonObject json : res.result()) { + data.add(new MuteData(MuteReason.valueOf(json.getString("reason")), + UUID.fromString(json.getString("uuid")), + UUID.fromString(json.getString("muter")), + json.getInstant("date"))); + } + client.close(); + future.complete(data); + } + }); + return future; + } + + public CompletableFuture getRankFromDatabase() { + CompletableFuture future = new CompletableFuture<>(); + getObjectFromDatabase("rank").whenComplete((entries, throwable) -> + future.complete(Rank.valueOf(entries.getString("rank")))); + return future; + } + + private Rank rank; + public Rank getRank() { - return Rank.valueOf(getStringFromDatabase("rank")); + if (rank == null) { + getRankFromDatabase().whenComplete((rank1, throwable) -> rank = rank1); + } + return rank; } public void setRank(Rank rank) { @@ -229,17 +303,19 @@ public class DatabasePlayer { return getRank().getValue() >= rank.getValue(); } - public boolean isAllowed(Group group) throws Exception { - if(getRank().getGroup() == Group.None) throw new Exception("The group None is not supported"); + public boolean isAllowed(Group group) { return getRank().getGroup() == group; } - public boolean hasPlayedBefore() { - FindIterable cursor = playerCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); + public CompletableFuture hasPlayedBefore() { + CompletableFuture future = new CompletableFuture<>(); + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.findOne("players", new JsonObject().put("uuid", uuid.toString()), new JsonObject("uuid"), res -> { + client.close(); + future.complete(res.succeeded()); + }); - Document obj = cursor.first(); - return obj != null; + return future; } public void setTSID(String id) { @@ -254,185 +330,175 @@ public class DatabasePlayer { setInDatabase("experience", experience); } - private void setFoundSecrets(ArrayList secrets) { - setInDatabase("foundSecrets", secrets); + public CompletableFuture getFirstLogin() { + CompletableFuture future = new CompletableFuture<>(); + getObjectFromDatabase("firstLogin").whenComplete((entries, throwable) -> { + future.complete(entries.getInstant("firstLogin")); + }); + return future; } - public void addSecret(String name) { - ArrayList list = getFoundSecrets(); - list.add(name); - setFoundSecrets(list); + public CompletableFuture getLastLogin() { + CompletableFuture future = new CompletableFuture<>(); + getObjectFromDatabase("lastLogin").whenComplete((entries, throwable) -> { + future.complete(entries.getInstant("lastLogin")); + }); + return future; } - private void setFoundEggs(ArrayList eggs) { - setInDatabase("foundEggs", eggs); + public CompletableFuture getLastOnline() { + CompletableFuture future = new CompletableFuture<>(); + getObjectFromDatabase("lastOnline").whenComplete((entries, throwable) -> { + future.complete(entries.getInstant("lastOnline")); + }); + return future; } - public void addEgg(String name) { - ArrayList list = getFoundEggs(); - list.add(name); - setFoundEggs(list); + public CompletableFuture getLastIP() { + CompletableFuture future = new CompletableFuture<>(); + getObjectFromDatabase("lastIP").whenComplete((entries, throwable) -> { + future.complete(entries.getString("lastIP")); + }); + return future; } - public Date getFirstLogin() { - return getDateFromDatabase("firstLogin"); + public CompletableFuture getTSID() { + CompletableFuture future = new CompletableFuture<>(); + getObjectFromDatabase("tsid").whenComplete((entries, throwable) -> { + future.complete(entries.getString("tsid")); + }); + return future; } - public Date getLastLogin() { - return getDateFromDatabase("lastLogin"); + public CompletableFuture getTimesJoined() { + CompletableFuture future = new CompletableFuture<>(); + getObjectFromDatabase("timesJoined").whenComplete((entries, throwable) -> { + future.complete(entries.getInteger("TimesJoined")); + }); + return future; } - public Date getLastOnline() { - return getDateFromDatabase("lastOnline"); + public CompletableFuture getCoins() { + CompletableFuture future = new CompletableFuture<>(); + getObjectFromDatabase("coins").whenComplete((entries, throwable) -> { + future.complete(entries.getInteger("coins")); + }); + return future; } - public String getLastIP() { - return getStringFromDatabase("lastIP"); - } - - public String getTSID() { - return getStringFromDatabase("tsid"); - } - - public int getTimesJoined() { - return getIntegerFromDatabase("timesJoined"); - } - - public int getCoins() { - return getIntegerFromDatabase("coins"); - } - - public int getExperience() { - return getIntegerFromDatabase("experience"); - } - - public int getSecrets() { - return getFoundSecrets().size(); - } - - private ArrayList getFoundSecrets() { - return getArrayListFromDatabase("foundSecrets"); - } - - public int getEggs() { - return getFoundEggs().size(); - } - - private ArrayList getFoundEggs() { - return getArrayListFromDatabase("foundEggs"); + public CompletableFuture getExperience() { + CompletableFuture future = new CompletableFuture<>(); + getObjectFromDatabase("experience").whenComplete((entries, throwable) -> { + future.complete(entries.getInteger("experience")); + }); + return future; } private void setFriends(Collection friends) { List list = friends.stream().map(FriendData::getUuid).collect(Collectors.toCollection(LinkedList::new)); - friendCollection.updateOne(new Document("uuid", uuid.toString()), new Document("$set", new Document("friends", list))); + + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.findOneAndUpdate("friends", new JsonObject().put("uuid", uuid.toString()), + new JsonObject().put("$set", new JsonObject().put("friends", list)), res -> { + if (res.failed()) { + try { + throw res.cause(); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + } + }); } - public Collection getFriends() { - FindIterable cursor = friendCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - - Document doc = cursor.first(); - if (doc == null) return null; - - LinkedList list = (LinkedList) doc.get("friends"); - - return list.stream().map(FriendData::new).collect(Collectors.toCollection(LinkedList::new)); + public CompletableFuture> getFriends() { + CompletableFuture> future = new CompletableFuture<>(); + Collection data = new LinkedList<>(); + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.findOne("friends", new JsonObject().put("uuid", uuid.toString()), null, res -> { + if (res.succeeded()) { + for (Object uuid : res.result().getJsonArray("friends")) { + data.add(new FriendData(UUID.fromString(String.valueOf(uuid)))); + } + client.close(); + future.complete(data); + } + }); + return future; } - public boolean isFriend(UUID uuid) { - for(FriendData friend : getFriends()) { - if(friend.getUuid() == uuid) return true; - } - return false; + public CompletableFuture isFriend(UUID uuid) { + CompletableFuture future = new CompletableFuture<>(); + getFriends().whenComplete((friendData, throwable) -> { + for (FriendData data : friendData) { + if (data.getUuid() == uuid) future.complete(true); + } + future.complete(false); + }); + + return future; } public void addFriend(UUID uuid) { - Collection list = getFriends(); - assert list != null; - list.add(new FriendData(uuid)); - setFriends(list); + getFriends().whenComplete((friendData, throwable) -> { + friendData.add(new FriendData(uuid)); + setFriends(friendData); + }); } public void removeFriend(UUID uuid) { - Collection list = getFriends(); - assert list != null; - list.remove(new FriendData(uuid)); - setFriends(list); + getFriends().whenComplete((friendData, throwable) -> { + friendData.remove(new FriendData(uuid)); + setFriends(friendData); + }); + } public void addCoins(int coins) { - setCoins(getCoins() + coins); + getCoins().whenComplete((integer, throwable) -> { + setCoins(integer + coins); + }); } public void substractCoins(int coins) { - setCoins(getCoins() - coins); + getCoins().whenComplete((integer, throwable) -> { + setCoins(integer - coins); + }); } - public boolean isOnline() { - FindIterable cursor = onlinePlayerCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - Document doc = cursor.first(); - return doc != null; - } - - public int getBoardID() { - return getIntegerFromDatabase("boardID"); + public CompletableFuture getBoardID() { + CompletableFuture future = new CompletableFuture<>(); + getObjectFromDatabase("boardID").whenComplete((entries, throwable) -> { + future.complete(entries.getInteger("boardID")); + }); + return future; } public void setBoardID(int id) { setInDatabase("boardID", id); } - //database handling methods public void setInDatabase(String name, Object obj) { - playerCollection.updateOne(new Document("uuid", uuid.toString()), new Document("$set", new Document(name, obj))); + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.findOneAndUpdate("players", new JsonObject().put("uuid", uuid.toString()), + new JsonObject().put("$set", new JsonObject().put(name, obj)), res -> { + if (res.failed()) { + try { + throw res.cause(); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + } + client.close(); + }); } - public Object getObjectFromDatabase(String name) { - FindIterable cursor = playerCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - - Document doc = cursor.first(); - if (doc == null) return null; - - return doc.get(name); - } - - public int getIntegerFromDatabase(String name) { - FindIterable cursor = playerCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - - Document doc = cursor.first(); - if (doc == null) return 0; - - return doc.getInteger(name); - } - - public String getStringFromDatabase(String name) { - FindIterable cursor = playerCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - - Document doc = cursor.first(); - if (doc == null) return null; - - return doc.getString(name); - } - - public Date getDateFromDatabase(String name) { - FindIterable cursor = playerCollection.find(new Document("uuid", uuid.toString())); - cursor.cursorType(CursorType.NonTailable); - - Document doc = cursor.first(); - if (doc == null) return null; - - return doc.getDate(name); - } - - public ArrayList getArrayListFromDatabase(String name) { - return (ArrayList) getObjectFromDatabase(name); - } - - public Map getMapFromDatabase(String name) { - return (Map) getObjectFromDatabase(name); + public CompletableFuture getObjectFromDatabase(String name) { + CompletableFuture future = new CompletableFuture<>(); + MongoClient client = Commons.getCommons().getDatabaseManager().getMongoDB().getClient(); + client.findOne("players", new JsonObject().put("uuid", uuid.toString()), new JsonObject(name), res -> { + client.close(); + future.complete(res.result()); + }); + return future; } } \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/player/MongoPlayer.java b/src/main/java/eu/univento/commons/player/MongoPlayer.java deleted file mode 100644 index b4810cc..0000000 --- a/src/main/java/eu/univento/commons/player/MongoPlayer.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2017 univento.eu - All rights reserved - * You are not allowed to use, distribute or modify this code - */ - -package eu.univento.commons.player; - -/** - * @author joethei - * @version 1.0 - */ - -import lombok.Getter; -import org.bson.types.ObjectId; -import org.mongodb.morphia.annotations.*; - -import java.util.UUID; - -@Getter -@Entity("players") -@Indexes(@Index(value = "lastName", fields = @Field("lastName"))) -public class MongoPlayer { - @Id private ObjectId id; - private UUID uuid; - private String lastName; -} \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/player/ban/BanData.java b/src/main/java/eu/univento/commons/player/ban/BanData.java index c76146f..4620317 100644 --- a/src/main/java/eu/univento/commons/player/ban/BanData.java +++ b/src/main/java/eu/univento/commons/player/ban/BanData.java @@ -6,6 +6,7 @@ import org.joda.time.Period; import org.joda.time.format.PeriodFormatter; import org.joda.time.format.PeriodFormatterBuilder; +import java.time.Instant; import java.util.Date; import java.util.UUID; @@ -18,10 +19,10 @@ public class BanData { private BanReason reason; private UUID banner; private String customMessage; - private Date unbanDate; + private Instant unbanDate; private String proof; - public BanData(BanReason reason, UUID banner, String customMessage, Date unbanDate, String proof) { + public BanData(BanReason reason, UUID banner, String customMessage, Instant unbanDate, String proof) { this.reason = reason; this.banner = banner; this.customMessage = customMessage; @@ -45,7 +46,7 @@ public class BanData { return customMessage; } - public Date getUnbanDate() { + public Instant getUnbanDate() { return unbanDate; } @@ -61,7 +62,7 @@ public class BanData { public String getTimeTillUnban() { assert getUnbanDate() != null; - final DateTime end = new DateTime(getUnbanDate().getTime()); + final DateTime end = new DateTime(getUnbanDate()); final DateTime now = new DateTime(new Date().getTime()); Period period = new Period(now, end); PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroAlways().minimumPrintedDigits(2) diff --git a/src/main/java/eu/univento/commons/player/hacks/HackData.java b/src/main/java/eu/univento/commons/player/hacks/HackData.java deleted file mode 100644 index cb9c1fe..0000000 --- a/src/main/java/eu/univento/commons/player/hacks/HackData.java +++ /dev/null @@ -1,196 +0,0 @@ -package eu.univento.commons.player.hacks; - -import eu.univento.commons.helpers.Location; -import eu.univento.commons.player.DatabasePlayer; - -/** - * @author joethei - * @version 0.1 - */ -public class HackData { - - private DatabasePlayer player; - private Location lastLocation; - private Location realLocation; - private boolean lastHealth; - private long lastPlacedBlock; - private long lastBow; - private long lastRegen; - private long lastAnimation; - private long lastForcefield; - private long lastY; - private long highestY; - private boolean ascending; - private boolean descending; - private Location lastBlockLocation; - private double blocksMoved; - private int fakePlayer; - private long lastTimeFakePlayerAttack; - private long lastFood; - private long lastInventory; - private long lastNotification; - - public HackData(DatabasePlayer player) { - this.player = player; - } - - public DatabasePlayer getPlayer() { - return player; - } - - public void setPlayer(DatabasePlayer player) { - this.player = player; - } - - public Location getLastLocation() { - return lastLocation; - } - - public void setLastLocation(Location lastLocation) { - this.lastLocation = lastLocation; - } - - public Location getRealLocation() { - return realLocation; - } - - public void setRealLocation(Location realLocation) { - this.realLocation = realLocation; - } - - public boolean isLastHealth() { - return lastHealth; - } - - public void setLastHealth(boolean lastHealth) { - this.lastHealth = lastHealth; - } - - public long getLastPlacedBlock() { - return lastPlacedBlock; - } - - public void setLastPlacedBlock(long lastPlacedBlock) { - this.lastPlacedBlock = lastPlacedBlock; - } - - public long getLastBow() { - return lastBow; - } - - public void setLastBow(long lastBow) { - this.lastBow = lastBow; - } - - public long getLastRegen() { - return lastRegen; - } - - public void setLastRegen(long lastRegen) { - this.lastRegen = lastRegen; - } - - public long getLastAnimation() { - return lastAnimation; - } - - public void setLastAnimation(long lastAnimation) { - this.lastAnimation = lastAnimation; - } - - public long getLastForcefield() { - return lastForcefield; - } - - public void setLastForcefield(long lastForcefield) { - this.lastForcefield = lastForcefield; - } - - public long getLastY() { - return lastY; - } - - public void setLastY(long lastY) { - this.lastY = lastY; - } - - public long getHighestY() { - return highestY; - } - - public void setHighestY(long highestY) { - this.highestY = highestY; - } - - public boolean isAscending() { - return ascending; - } - - public void setAscending(boolean ascending) { - this.ascending = ascending; - } - - public boolean isDescending() { - return descending; - } - - public void setDescending(boolean descending) { - this.descending = descending; - } - - public Location getLastBlockLocation() { - return lastBlockLocation; - } - - public void setLastBlockLocation(Location lastBlockLocation) { - this.lastBlockLocation = lastBlockLocation; - } - - public double getBlocksMoved() { - return blocksMoved; - } - - public void setBlocksMoved(double blocksMoved) { - this.blocksMoved = blocksMoved; - } - - public int getFakePlayer() { - return fakePlayer; - } - - public void setFakePlayer(int fakePlayer) { - this.fakePlayer = fakePlayer; - } - - public long getLastTimeFakePlayerAttack() { - return lastTimeFakePlayerAttack; - } - - public void setLastTimeFakePlayerAttack(long lastTimeFakePlayerAttack) { - this.lastTimeFakePlayerAttack = lastTimeFakePlayerAttack; - } - - public long getLastFood() { - return lastFood; - } - - public void setLastFood(long lastFood) { - this.lastFood = lastFood; - } - - public long getLastInventory() { - return lastInventory; - } - - public void setLastInventory(long lastInventory) { - this.lastInventory = lastInventory; - } - - public long getLastNotification() { - return lastNotification; - } - - public void setLastNotification(long lastNotification) { - this.lastNotification = lastNotification; - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/player/kick/KickData.java b/src/main/java/eu/univento/commons/player/kick/KickData.java index 3e113ba..191c44a 100644 --- a/src/main/java/eu/univento/commons/player/kick/KickData.java +++ b/src/main/java/eu/univento/commons/player/kick/KickData.java @@ -2,7 +2,7 @@ package eu.univento.commons.player.kick; import eu.univento.commons.player.uuid.NameFetcher; -import java.util.Date; +import java.time.Instant; import java.util.UUID; /** @@ -12,10 +12,10 @@ import java.util.UUID; public class KickData { private KickReason reason; - private Date date; + private Instant date; private UUID kicker; - public KickData(KickReason reason, Date date, UUID kicker) { + public KickData(KickReason reason, Instant date, UUID kicker) { this.reason = reason; this.date = date; this.kicker = kicker; @@ -25,7 +25,7 @@ public class KickData { return reason; } - public Date getDate() { + public Instant getDate() { return date; } diff --git a/src/main/java/eu/univento/commons/player/language/Language.java b/src/main/java/eu/univento/commons/player/language/Language.java deleted file mode 100644 index 7096fd9..0000000 --- a/src/main/java/eu/univento/commons/player/language/Language.java +++ /dev/null @@ -1,49 +0,0 @@ -package eu.univento.commons.player.language; - -import com.zaxxer.sansorm.OrmElf; -import com.zaxxer.sansorm.SqlClosure; -import eu.univento.commons.Commons; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; - -/** - * @author joethei - * @version 2.0 - */ - -//TODO: optimize -public class Language { - - private HashMap translations; - - public Language(Locale locale) { - translations = new HashMap<>(); - try { - List translationList = new SqlClosure>() { - public List execute(Connection connection) throws SQLException { - PreparedStatement statement = connection.prepareStatement("SELECT * FROM translations;"); - return OrmElf.statementToList(statement, Translation.class); - } - }.execute(Commons.getCommons().getDatabaseManager().getMySQL().getConnection()); - - for(Translation translation : translationList) { - translations.put(translation.getIdentifier(), translation.getTranslation(locale)); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public String getWord(String keyword) { - return translations.get(keyword); - } - - public String getMessage(MessageConstant constant) { - return translations.get(constant.getName()); - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/player/language/Languages.java b/src/main/java/eu/univento/commons/player/language/Languages.java deleted file mode 100644 index c029063..0000000 --- a/src/main/java/eu/univento/commons/player/language/Languages.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017 univento.eu - All rights reserved - * You are not allowed to use, distribute or modify this code - */ - -package eu.univento.commons.player.language; - -import java.util.Locale; - -/** - * @author joethei - * @version 1.0 - */ -public class Languages { - - private static Language german; - private static Language english; - - public static void init() { - german = new Language(Locale.GERMAN); - english = new Language(Locale.ENGLISH); - } - - //TODO: optimize - public static Language getLanguage(String language) { - if(language.equals("DE")) return german; - if(language.equals("EN")) return english; - return null; - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/player/language/Translation.java b/src/main/java/eu/univento/commons/player/language/Translation.java deleted file mode 100644 index d3072ab..0000000 --- a/src/main/java/eu/univento/commons/player/language/Translation.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017 univento.eu - All rights reserved - * You are not allowed to use, distribute or modify this code - */ -package eu.univento.commons.player.language; - -import lombok.Getter; - -import javax.persistence.Id; -import javax.persistence.Table; -import java.util.Locale; - -/** - * @author joethei - * @version 1.0 - */ - -@Getter -@Table(name="translations") -class Translation { - @Id private int id; - private String identifier; - private String german; - private String english; - - //TODO: optimize - String getTranslation(Locale locale) { - if(locale == Locale.GERMAN) return german; - if(locale == Locale.ENGLISH) return english; - return null; - } -} \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/player/mute/MuteData.java b/src/main/java/eu/univento/commons/player/mute/MuteData.java index 9c45745..975628c 100644 --- a/src/main/java/eu/univento/commons/player/mute/MuteData.java +++ b/src/main/java/eu/univento/commons/player/mute/MuteData.java @@ -6,7 +6,7 @@ import org.joda.time.Period; import org.joda.time.format.PeriodFormatter; import org.joda.time.format.PeriodFormatterBuilder; -import java.util.Date; +import java.time.Instant; import java.util.UUID; /** @@ -18,9 +18,9 @@ public class MuteData { private MuteReason reason; private UUID player; private UUID muter; - private Date date; + private Instant date; - public MuteData(MuteReason reason, UUID player, UUID muter, Date date) { + public MuteData(MuteReason reason, UUID player, UUID muter, Instant date) { this.reason = reason; this.player = player; this.muter = muter; @@ -39,7 +39,7 @@ public class MuteData { return muter; } - public Date getDate() { + public Instant getDate() { return date; } @@ -51,8 +51,8 @@ public class MuteData { public String getTimeTillUnmute() { assert getDate() != null; - final DateTime end = new DateTime(getDate().getTime()); - final DateTime now = new DateTime(new Date().getTime()); + final DateTime end = new DateTime(getDate()); + final DateTime now = new DateTime(Instant.now()); Period period = new Period(now, end); PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroAlways().minimumPrintedDigits(2) .appendYears().appendSuffix(" Jahr", " Jahre") diff --git a/src/main/java/eu/univento/commons/player/rank/Rank.java b/src/main/java/eu/univento/commons/player/rank/Rank.java index 14e028e..05933ef 100644 --- a/src/main/java/eu/univento/commons/player/rank/Rank.java +++ b/src/main/java/eu/univento/commons/player/rank/Rank.java @@ -16,21 +16,21 @@ public enum Rank { Admin(18, 0, 0, Group.None, "a", "§4", "§8[§4Admin§8] §4", " §8»§7 ", "§4Admin | "), - SrDeveloper(17, 0, 0, Group.Developer, "b"), - Developer(16, 0, 0, Group.Developer, "c"), - JrDeveloper(15, 0, 0, Group.Developer, "d"), + SrDeveloper(11, 0, 0, Group.Developer, "b"), + Developer(10, 0, 0, Group.Developer, "c"), + JrDeveloper(9, 0, 0, Group.Developer, "d"), SrBuilder(8, 0, 0, Group.Builder, "e"), Builder(7, 0, 0, Group.Builder, "f"), JrBuilder(6, 0, 0, Group.Builder, "g"), - SrModerator(14, 0, 0, Group.Moderator, "h"), - Moderator(13, 0, 0, Group.Moderator, "i"), - JrModerator(12, 0, 0, Group.Moderator, "j"), + SrModerator(17, 0, 0, Group.Moderator, "h"), + Moderator(16, 0, 0, Group.Moderator, "i"), + JrModerator(15, 0, 0, Group.Moderator, "j"), - SrSupporter(11, 0, 0, Group.Supporter, "k"), - Supporter(10, 0, 0, Group.Supporter, "l"), - JrSupporter(9, 0, 0, Group.Supporter, "m"), + SrSupporter(14, 0, 0, Group.Supporter, "k"), + Supporter(13, 0, 0, Group.Supporter, "l"), + JrSupporter(12, 0, 0, Group.Supporter, "m"), Graphic(5, 0, 0, Group.Design, "n"), Sound(4, 0, 0, Group.Design, "o"), diff --git a/src/main/java/eu/univento/commons/player/settings/PlayerSettings.java b/src/main/java/eu/univento/commons/player/settings/PlayerSettings.java index bbe8dd8..d79d833 100644 --- a/src/main/java/eu/univento/commons/player/settings/PlayerSettings.java +++ b/src/main/java/eu/univento/commons/player/settings/PlayerSettings.java @@ -1,137 +1,144 @@ package eu.univento.commons.player.settings; import eu.univento.commons.player.DatabasePlayer; - -import java.io.Serializable; -import java.util.Map; +import io.vertx.core.json.JsonObject; /** * @author joethei - * @version 1.0 + * @version 1.1 */ public class PlayerSettings { private DatabasePlayer player; + private JsonObject json; - public PlayerSettings(DatabasePlayer player) { + public PlayerSettings(DatabasePlayer player, JsonObject json) { this.player = player; + this.json = json; } public String getPlayerVisibility() { - return (String) getSettings().get("playerVisibility"); + return json.getString("playerVisibility"); } public boolean hasInventoryAnimationEnabled() { - return (boolean) getSettings().get("inventoryAnimation"); + return json.getBoolean("inventoryAnimation"); } public boolean hasTeleportAnimationEnabled() { - return (boolean) getSettings().get("teleportAnimation"); + return json.getBoolean("teleportAnimation"); } public boolean hasPartyRequestsEnabled() { - return (boolean) getSettings().get("partyRequests"); + return json.getBoolean("partyRequests"); } public boolean hasFriendRequestsEnabled() { - return (boolean) getSettings().get("friendRequests"); + return json.getBoolean("friendRequests"); } public boolean hasFriendJumpEnabled() { - return (boolean) getSettings().get("friendJump"); + return json.getBoolean("friendJump"); } public boolean hasChatSoundsEnabled() { - return (boolean) getSettings().get("chatSounds"); + return json.getBoolean("chatSounds"); } public boolean hasEffectsEnabled() { - return (boolean) getSettings().get("effects"); + return json.getBoolean("effects"); } public boolean hasStoryModeEnabled() { - return (boolean) getSettings().get("storyMode"); + return json.getBoolean("storyMode"); } public String getLanguage() { - return (String) getSettings().get("language"); + return json.getString("language"); } public boolean hasTsMoveEnabled() { - return (boolean) getSettings().get("tsMove"); + return json.getBoolean("tsMove"); } public boolean hasScoreboardEnabled() { - return (boolean) getSettings().get("scoreboard"); - } - - public void setPlayerVisibility(String visibility) { - setSetting("playerVisibility", visibility); - } - - public void setInventoryAnimation(boolean animation) { - setSetting("inventoryAnimation", animation); - } - - public void setTeleportAnimation(boolean animation) { - setSetting("teleportAnimation", animation); - } - - public void setPartyRequests(boolean requests) { - setSetting("partyRequests", requests); - } - - public void setFriendRequests(boolean requests) { - setSetting("friendRequests", requests); - } - - public void setFriendJump(boolean jump) { - setSetting("friendJump", jump); - } - - public void setChatSounds(boolean sounds) { - setSetting("chatSounds", sounds); - } - - public void setEffects(boolean effects) { - setSetting("effects", effects); - } - - public void setStoryMode(boolean storyMode) { - setSetting("storyMode", storyMode); - } - - public void setLanguage(String language) { - setSetting("language", language); - } - - public void setTsMove(boolean tsMove) { - setSetting("tsMove", tsMove); - } - - public void setScoreboard(boolean scoreboard) { - setSetting("scoreboard", scoreboard); + return json.getBoolean("scoreboard"); } public boolean isNicked() { - return (boolean) getSettings().get("nicked"); + return json.getBoolean("nicked"); + } + + + + public void setPlayerVisibility(String visibility) { + json.put("playerVisibility", visibility); + update(); + } + + public void setInventoryAnimation(boolean animation) { + json.put("inventoryAnimation", animation); + update(); + } + + public void setTeleportAnimation(boolean animation) { + json.put("teleportAnimation", animation); + update(); + } + + public void setPartyRequests(boolean requests) { + json.put("partyRequests", requests); + update(); + } + + public void setFriendRequests(boolean requests) { + json.put("friendRequests", requests); + update(); + } + + public void setFriendJump(boolean jump) { + json.put("friendJump", jump); + update(); + } + + public void setChatSounds(boolean sounds) { + json.put("chatSounds", sounds); + update(); + } + + public void setEffects(boolean effects) { + json.put("effects", effects); + update(); + } + + public void setStoryMode(boolean storyMode) { + json.put("storyMode", storyMode); + update(); + } + + public void setLanguage(String language) { + json.put("language", language); + update(); + } + + public void setTsMove(boolean tsMove) { + json.put("tsMove", tsMove); + update(); + } + + public void setScoreboard(boolean scoreboard) { + json.put("scoreboard", scoreboard); + update(); } public void setNickStatus(boolean nicked) { - setSetting("nicked", nicked); + json.put("nicked", nicked);update(); + update(); + } - private Map getSettings() { - return player.getMapFromDatabase("Settings"); + private void update() { + player.setInDatabase("Settings", json); } - private void setSettings(Map settings) { - player.setInDatabase("Settings", settings); - } - - private void setSetting(String name, Serializable setting) { - Map map = getSettings(); - map.put(name, setting); - setSettings(map); - } } \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/player/statistics/GameStat.java b/src/main/java/eu/univento/commons/player/statistics/GameStat.java new file mode 100644 index 0000000..6da6143 --- /dev/null +++ b/src/main/java/eu/univento/commons/player/statistics/GameStat.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2017 univento.eu - All rights reserved + * You are not allowed to use, distribute or modify this code + */ + +package eu.univento.commons.player.statistics; + +/** + * @author joethei + * @version 0.1 + */ +public interface GameStat { + + //@Getter ServerType type = null; +} \ No newline at end of file diff --git a/src/main/java/eu/univento/commons/player/statistics/GameStats.java b/src/main/java/eu/univento/commons/player/statistics/GameStats.java index 4436dbc..c96c5b1 100644 --- a/src/main/java/eu/univento/commons/player/statistics/GameStats.java +++ b/src/main/java/eu/univento/commons/player/statistics/GameStats.java @@ -20,7 +20,9 @@ public class GameStats { public GameStats(ServerType type, DatabasePlayer player) { this.type = type; this.player = player; - stats = player.getMapFromDatabase(type.getName()); + player.getObjectFromDatabase(type.getName()).whenComplete((entries, throwable) -> { + //TODO: add stuff here or change the entire stats system + }); } public Long getStat(String name) { diff --git a/src/main/java/eu/univento/commons/player/warn/WarnData.java b/src/main/java/eu/univento/commons/player/warn/WarnData.java index c853f6a..f0cfedc 100644 --- a/src/main/java/eu/univento/commons/player/warn/WarnData.java +++ b/src/main/java/eu/univento/commons/player/warn/WarnData.java @@ -2,7 +2,7 @@ package eu.univento.commons.player.warn; import eu.univento.commons.player.uuid.NameFetcher; -import java.util.Date; +import java.time.Instant; import java.util.UUID; /** @@ -13,10 +13,10 @@ public class WarnData { private WarnReason reason; private UUID warner; - private Date date; + private Instant date; private String proof; - public WarnData(WarnReason reason, UUID warner, Date date, String proof) { + public WarnData(WarnReason reason, UUID warner, Instant date, String proof) { this.reason = reason; this.warner = warner; this.date = date; @@ -31,7 +31,7 @@ public class WarnData { return warner; } - public Date getDate() { + public Instant getDate() { return date; } diff --git a/src/main/java/eu/univento/commons/utils/Pool.java b/src/main/java/eu/univento/commons/utils/Pool.java new file mode 100644 index 0000000..96f23fd --- /dev/null +++ b/src/main/java/eu/univento/commons/utils/Pool.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2017 univento.eu - All rights reserved + * You are not allowed to use, distribute or modify this code + */ + +package eu.univento.commons.utils; + +import java.util.*; + +/** + * Created by Matthew on 01/11/2014. + * @author sainttx + */ +public class Pool implements Cloneable { + + /* + * A map which contains all the values and their pool amounts + */ + private Map pooling = new LinkedHashMap<>(); + + /** + * A random used for picking a winner + */ + private Random random = new Random(); + + /** + * Adds an Object to the Pool + * @param add The Object to add + * @param amount The amount of tickets the Object has in the Pool + */ + public void add(T add, Integer amount) { + pooling.put(add, amount); + } + + /** + * Removes an Object from the Pool + * @param remove The Object to remove + */ + public void remove(T remove) { + pooling.remove(remove); + } + + /** + * Gets the number of tickets an object has + * in the pool + * @param t the object + * @return the amount of tickets the object has, will return -1 if the object is + * not in the pool + */ + public int getTickets(T t) { + if (!pooling.containsKey(t)) { + return -1; + } + return pooling.get(t); + } + + /** + * Gets all of the rewards in the pool + * @return a set of all rewards in the pool + */ + public Set getRewards() { + return pooling.keySet(); + } + + /** + * Chooses an Object from the Pool + * @return The winner of the Pool + */ + public T pick() { + int size = random.nextInt(this.getSize()); + + Map pooling = new HashMap<>(this.pooling); + for (Map.Entry poolEntry : pooling.entrySet()) { + if ((size -= poolEntry.getValue()) <= 0) { + return poolEntry.getKey(); + } + } + + return pooling.keySet().iterator().next(); + } + + /** + * Returns the total amount of tickets inside the Pool + * @return size + */ + public int getSize() { + int ret = 0; + + for (Integer amount : pooling.values()) { + ret += amount; + } + + return ret; + } + + @Override + public Pool clone() { + Pool pool = new Pool<>(); + pool.pooling = new HashMap<>(this.pooling); + return pool; + } + + @Override + public int hashCode() { + return 31 * pooling.hashCode(); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Pool)) { + return false; + } + + Pool pool = (Pool) o; + return this.pooling.equals(pool.pooling); + } +}