~ Async Database Handling

This commit is contained in:
Johannes Theiner 2017-04-07 17:10:36 +02:00
parent c2bb13da73
commit 24f8d0dcec
26 changed files with 678 additions and 988 deletions

View File

@ -0,0 +1,3 @@
Was hast du gemacht als der Bug aufgetreten ist ?
Ausgabe des `/bureport` Befehls:

View File

View File

@ -12,16 +12,35 @@
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.projectlombok:lombok:1.14.8" level="project" />
<orderEntry type="library" name="Maven: org.mongodb.morphia:morphia:1.3.1" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongo-java-driver:3.4.0" level="project" />
<orderEntry type="library" name="Maven: cglib:cglib-nodep:2.2.2" level="project" />
<orderEntry type="library" name="Maven: com.thoughtworks.proxytoys:proxytoys:1.0" level="project" />
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:2.4.5" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.16" level="project" />
<orderEntry type="library" name="Maven: com.zaxxer:SansOrm:1.0" level="project" />
<orderEntry type="library" name="Maven: javax.persistence:persistence-api:1.0.2" level="project" />
<orderEntry type="library" name="Maven: redis.clients:jedis:2.9.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-pool2:2.4.2" level="project" />
<orderEntry type="library" name="Maven: io.vertx:vertx-core:3.4.1" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-common:4.1.8.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-buffer:4.1.8.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-transport:4.1.8.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-handler:4.1.8.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-codec:4.1.8.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-handler-proxy:4.1.8.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-codec-socks:4.1.8.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-codec-http:4.1.8.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-codec-http2:4.1.8.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-resolver:4.1.8.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-resolver-dns:4.1.8.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-codec-dns:4.1.8.Final" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.7.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.7.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.7.0" level="project" />
<orderEntry type="library" name="Maven: io.vertx:vertx-redis-client:3.4.1" level="project" />
<orderEntry type="library" name="Maven: io.vertx:vertx-mysql-postgresql-client:3.4.1" level="project" />
<orderEntry type="library" name="Maven: io.vertx:vertx-sql-common:3.4.1" level="project" />
<orderEntry type="library" name="Maven: org.scala-lang:scala-library:2.12.1" level="project" />
<orderEntry type="library" name="Maven: com.github.mauricio:postgresql-async_2.12:0.2.21" level="project" />
<orderEntry type="library" name="Maven: com.github.mauricio:db-async-common_2.12:0.2.21" level="project" />
<orderEntry type="library" name="Maven: org.joda:joda-convert:1.8.1" level="project" />
<orderEntry type="library" name="Maven: org.javassist:javassist:3.21.0-GA" level="project" />
<orderEntry type="library" name="Maven: com.github.mauricio:mysql-async_2.12:0.2.21" level="project" />
<orderEntry type="library" name="Maven: io.vertx:vertx-mongo-client:3.4.1" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongodb-driver-async:3.4.1" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongodb-driver-core:3.4.1" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:bson:3.4.1" level="project" />
<orderEntry type="library" name="Maven: com.google.code.gson:gson:2.3.1" level="project" />
<orderEntry type="library" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava:19.0" level="project" />

36
pom.xml
View File

@ -58,37 +58,25 @@
<artifactId>lombok</artifactId>
<version>1.14.8</version>
</dependency>
<!--
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>
-->
<dependency>
<groupId>org.mongodb.morphia</groupId>
<artifactId>morphia</artifactId>
<version>1.3.1</version>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.4.5</version>
<groupId>io.vertx</groupId>
<artifactId>vertx-redis-client</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>SansOrm</artifactId>
<version>1.0</version>
<groupId>io.vertx</groupId>
<artifactId>vertx-mysql-postgresql-client</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<groupId>io.vertx</groupId>
<artifactId>vertx-mongo-client</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>

View File

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

View File

@ -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<MongoDatabase> consumer) {
consumer.accept(mongoDB.getDatabase());
}
}

View File

@ -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<ResultSet> consumer) {
executor.execute(() -> {
ResultSet result;
result = mySQL.query(query);
ResultSet finalResult = result;
consumer.accept(finalResult);
});
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -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<Document> playerCollection;
private final MongoCollection<Document> friendCollection;
private final MongoCollection<Document> onlinePlayerCollection;
private final MongoCollection<Document> banCollection;
private final MongoCollection<Document> warnCollection;
private final MongoCollection<Document> kickCollection;
private final MongoCollection<Document> muteCollection;
private final MongoCollection<Document> 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<Profile> 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<PlayerSettings> getSettingsFromDatabase() {
CompletableFuture<PlayerSettings> 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<Ranking> getRanking() {
CompletableFuture<Ranking> 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<Document> 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<BanData> getBan() {
CompletableFuture<BanData> 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<Boolean> isBanned() {
CompletableFuture<Boolean> future = new CompletableFuture<>();
getBan().whenComplete((banData, throwable) -> future.complete(banData != null && !Instant.now().isAfter(banData.getUnbanDate())));
return future;
}
public Collection<BanData> getAllBans() {
FindIterable<Document> cursor = banCollection.find(new Document("uuid", uuid.toString()));
cursor.cursorType(CursorType.NonTailable);
Iterator<Document> iterator = cursor.iterator();
Collection<BanData> 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<Collection<BanData>> getAllBans() {
CompletableFuture<Collection<BanData>> future = new CompletableFuture<>();
Collection<BanData> 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<Document> 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<Boolean> isWarned() {
CompletableFuture<Boolean> 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<WarnData> getAllWarns() {
FindIterable<Document> cursor = warnCollection.find(new Document("uuid", uuid.toString()));
cursor.cursorType(CursorType.NonTailable);
Iterator<Document> iterator = cursor.iterator();
Collection<WarnData> 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<Collection<WarnData>> getAllWarns() {
CompletableFuture<Collection<WarnData>> future = new CompletableFuture<>();
Collection<WarnData> 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<KickData> getAllKicks() {
FindIterable<Document> cursor = kickCollection.find(new Document("uuid", uuid.toString()));
cursor.cursorType(CursorType.NonTailable);
Iterator<Document> iterator = cursor.iterator();
LinkedList<KickData> 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<Collection<KickData>> getAllKicks() {
CompletableFuture<Collection<KickData>> future = new CompletableFuture<>();
Collection<KickData> 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<Document> 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<MuteData> getAllMutes() {
FindIterable<Document> cursor = muteCollection.find(new Document("uuid", uuid.toString()));
cursor.cursorType(CursorType.NonTailable);
Iterator<Document> iterator = cursor.iterator();
LinkedList<MuteData> 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<Boolean> isMuted() {
CompletableFuture<Boolean> future = new CompletableFuture<>();
getMute().whenComplete((muteData, throwable) -> {
future.complete(muteData != null && !Instant.now().isAfter(muteData.getDate()));
});
return future;
}
public CompletableFuture<MuteData> getMute() {
CompletableFuture<MuteData> future = new CompletableFuture<>();
getAllMutes().whenComplete((muteData, throwable) -> {
for (MuteData data : muteData) {
if (Instant.now().isBefore(data.getDate())) future.complete(data);
}
});
return future;
}
public CompletableFuture<Collection<MuteData>> getAllMutes() {
CompletableFuture<Collection<MuteData>> future = new CompletableFuture<>();
Collection<MuteData> 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<Rank> getRankFromDatabase() {
CompletableFuture<Rank> 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<Document> cursor = playerCollection.find(new Document("uuid", uuid.toString()));
cursor.cursorType(CursorType.NonTailable);
public CompletableFuture<Boolean> hasPlayedBefore() {
CompletableFuture<Boolean> 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<String> secrets) {
setInDatabase("foundSecrets", secrets);
public CompletableFuture<Instant> getFirstLogin() {
CompletableFuture<Instant> future = new CompletableFuture<>();
getObjectFromDatabase("firstLogin").whenComplete((entries, throwable) -> {
future.complete(entries.getInstant("firstLogin"));
});
return future;
}
public void addSecret(String name) {
ArrayList<String> list = getFoundSecrets();
list.add(name);
setFoundSecrets(list);
public CompletableFuture<Instant> getLastLogin() {
CompletableFuture<Instant> future = new CompletableFuture<>();
getObjectFromDatabase("lastLogin").whenComplete((entries, throwable) -> {
future.complete(entries.getInstant("lastLogin"));
});
return future;
}
private void setFoundEggs(ArrayList<String> eggs) {
setInDatabase("foundEggs", eggs);
public CompletableFuture<Instant> getLastOnline() {
CompletableFuture<Instant> future = new CompletableFuture<>();
getObjectFromDatabase("lastOnline").whenComplete((entries, throwable) -> {
future.complete(entries.getInstant("lastOnline"));
});
return future;
}
public void addEgg(String name) {
ArrayList<String> list = getFoundEggs();
list.add(name);
setFoundEggs(list);
public CompletableFuture<String> getLastIP() {
CompletableFuture<String> future = new CompletableFuture<>();
getObjectFromDatabase("lastIP").whenComplete((entries, throwable) -> {
future.complete(entries.getString("lastIP"));
});
return future;
}
public Date getFirstLogin() {
return getDateFromDatabase("firstLogin");
public CompletableFuture<String> getTSID() {
CompletableFuture<String> future = new CompletableFuture<>();
getObjectFromDatabase("tsid").whenComplete((entries, throwable) -> {
future.complete(entries.getString("tsid"));
});
return future;
}
public Date getLastLogin() {
return getDateFromDatabase("lastLogin");
public CompletableFuture<Integer> getTimesJoined() {
CompletableFuture<Integer> future = new CompletableFuture<>();
getObjectFromDatabase("timesJoined").whenComplete((entries, throwable) -> {
future.complete(entries.getInteger("TimesJoined"));
});
return future;
}
public Date getLastOnline() {
return getDateFromDatabase("lastOnline");
public CompletableFuture<Integer> getCoins() {
CompletableFuture<Integer> 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<String> getFoundSecrets() {
return getArrayListFromDatabase("foundSecrets");
}
public int getEggs() {
return getFoundEggs().size();
}
private ArrayList<String> getFoundEggs() {
return getArrayListFromDatabase("foundEggs");
public CompletableFuture<Integer> getExperience() {
CompletableFuture<Integer> future = new CompletableFuture<>();
getObjectFromDatabase("experience").whenComplete((entries, throwable) -> {
future.complete(entries.getInteger("experience"));
});
return future;
}
private void setFriends(Collection<FriendData> friends) {
List<UUID> 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<FriendData> getFriends() {
FindIterable<Document> cursor = friendCollection.find(new Document("uuid", uuid.toString()));
cursor.cursorType(CursorType.NonTailable);
Document doc = cursor.first();
if (doc == null) return null;
LinkedList<UUID> list = (LinkedList<UUID>) doc.get("friends");
return list.stream().map(FriendData::new).collect(Collectors.toCollection(LinkedList::new));
public CompletableFuture<Collection<FriendData>> getFriends() {
CompletableFuture<Collection<FriendData>> future = new CompletableFuture<>();
Collection<FriendData> 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<Boolean> isFriend(UUID uuid) {
CompletableFuture<Boolean> 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<FriendData> 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<FriendData> 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<Document> 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<Integer> getBoardID() {
CompletableFuture<Integer> 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<Document> 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<Document> 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<Document> 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<Document> 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<String> getArrayListFromDatabase(String name) {
return (ArrayList<String>) getObjectFromDatabase(name);
}
public Map<String, Object> getMapFromDatabase(String name) {
return (Map<String, Object>) getObjectFromDatabase(name);
public CompletableFuture<JsonObject> getObjectFromDatabase(String name) {
CompletableFuture<JsonObject> 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;
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -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<String, String> translations;
public Language(Locale locale) {
translations = new HashMap<>();
try {
List<Translation> translationList = new SqlClosure<List<Translation>>() {
public List<Translation> 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());
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -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<String, Object> getSettings() {
return player.getMapFromDatabase("Settings");
private void update() {
player.setInDatabase("Settings", json);
}
private void setSettings(Map<String, Object> settings) {
player.setInDatabase("Settings", settings);
}
private void setSetting(String name, Serializable setting) {
Map<String, Object> map = getSettings();
map.put(name, setting);
setSettings(map);
}
}

View File

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

View File

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

View File

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

View File

@ -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<T> implements Cloneable {
/*
* A map which contains all the values and their pool amounts
*/
private Map<T, Integer> 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<T> 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<T, Integer> pooling = new HashMap<>(this.pooling);
for (Map.Entry<T, Integer> 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<T> clone() {
Pool<T> 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);
}
}