Bugfixes & Two more listeners [2.0.0-DEV]

- Async tasks for database.
- Proper save on disable.
- Debugging with inspect command.
- Database now manages to save and load data, data needs to be debugged.

Known bugs:
- CommandListener things every command is /
- LastGameMode is set to null when player joins
- NullPointerException: LoginTimes when player not online on inspect
- Some values are negative (Probably times)
- ServerData not updating properly
- (DataBase saves non-existent ids)
- LoginTimes is not updated
- LoginTimes not found from database with sqlite3
This commit is contained in:
Rsl1122 2016-12-31 16:41:28 +02:00
parent e903a5ac25
commit fa776d30fd
15 changed files with 486 additions and 196 deletions

View File

@ -8,8 +8,10 @@ import com.djrapitops.plan.database.databases.MySQLDB;
import com.djrapitops.plan.database.databases.SQLiteDB;
import com.djrapitops.plan.datahandlers.DataHandler;
import com.djrapitops.plan.datahandlers.listeners.PlanChatListener;
import com.djrapitops.plan.datahandlers.listeners.PlanCommandPreprocessListener;
import com.djrapitops.plan.datahandlers.listeners.PlanGamemodeChangeListener;
import com.djrapitops.plan.datahandlers.listeners.PlanPlayerListener;
import com.djrapitops.plan.datahandlers.listeners.PlanPlayerMoveListener;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
@ -72,7 +74,9 @@ public class Plan extends JavaPlugin {
log(MiscUtils.checkVersion());
getCommand("plan").setExecutor(new PlanCommand(this));
handler.handleReload();
logToFile("-- Server Start/Reload --");
log("Player Analytics Enabled.");
}
@ -94,7 +98,8 @@ public class Plan extends JavaPlugin {
@Override
public void onDisable() {
log("Saving cached data..");
handler.saveCachedData();
handler.saveCacheOnDisable();
db.close();
log("Player Analytics Disabled.");
}
@ -144,6 +149,8 @@ public class Plan extends JavaPlugin {
getServer().getPluginManager().registerEvents(new PlanChatListener(this), this);
getServer().getPluginManager().registerEvents(new PlanPlayerListener(this), this);
getServer().getPluginManager().registerEvents(new PlanGamemodeChangeListener(this), this);
getServer().getPluginManager().registerEvents(new PlanCommandPreprocessListener(this), this);
getServer().getPluginManager().registerEvents(new PlanPlayerMoveListener(this), this);
}
public DataHandler getHandler() {

View File

@ -7,16 +7,19 @@ import com.djrapitops.plan.command.CommandType;
import com.djrapitops.plan.command.SubCommand;
import com.djrapitops.plan.command.utils.DataFormatUtils;
import com.djrapitops.plan.command.utils.DataUtils;
import com.djrapitops.plan.database.ServerData;
import java.util.Date;
import com.djrapitops.plan.database.UserData;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static org.bukkit.Bukkit.getOfflinePlayer;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import static org.bukkit.Bukkit.getOfflinePlayer;
public class InspectCommand extends SubCommand {
@ -57,12 +60,31 @@ public class InspectCommand extends SubCommand {
ChatColor operatorColor = Phrase.COLOR_MAIN.color();
ChatColor textColor = Phrase.COLOR_SEC.color();
List<String> msgs = new ArrayList<>();
msgs.add(""+data.getLoginTimes());
msgs.add(""+data.getBedLocation().getBlockX());
msgs.add(""+data.getDemData().getGeoLocation());
msgs.add(""+data.getGmTimes().keySet().toString());
msgs.add(""+data.getIps().toString());
msgs.add(""+data.getLastGamemode());
msgs.add(""+data.getLastGmSwapTime());
msgs.add(""+data.getLastPlayed());
msgs.add(""+data.getLocation().getBlockX());
msgs.add(""+data.getNicknames().toString());
msgs.add(""+data.getRegistered());
msgs.add(""+data.getTimesKicked());
msgs.add(""+data.getUuid());
msgs.add(operatorColor+"SERVER");
ServerData sdata = plugin.getHandler().getServerData();
msgs.add(""+sdata.getCommandUsage().keySet().toString());
msgs.add(""+sdata.getNewPlayers());
msgs.add(""+sdata.getPlayersOnline());
//header
sender.sendMessage(textColor + "-- [" + operatorColor + "PLAN - Inspect results: " + playerName +" - took "+DataFormatUtils.formatTimeAmountSinceDate(refreshDate, new Date())+ textColor + "] --");
sender.sendMessage(data.getUuid().toString());
sender.sendMessage(data.getIps().toString());
sender.sendMessage(""+data.isBanned());
for (String message : msgs) {
sender.sendMessage(textColor+message);
}
sender.sendMessage(textColor + "-- o --");
return true;

View File

@ -7,6 +7,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import org.bukkit.GameMode;
import static org.bukkit.plugin.java.JavaPlugin.getPlugin;
public class MiscUtils {
@ -58,4 +59,22 @@ public class MiscUtils {
}
return result;
}
public static GameMode parseGM(String string) {
String survival = GameMode.SURVIVAL.name();
String creative = GameMode.CREATIVE.name();
String adventure = GameMode.ADVENTURE.name();
String spectator = GameMode.SPECTATOR.name();
if (string.equalsIgnoreCase(survival)) {
return GameMode.SURVIVAL;
} else if (string.equalsIgnoreCase(creative)) {
return GameMode.CREATIVE;
} else if (string.equalsIgnoreCase(adventure)) {
return GameMode.ADVENTURE;
} else if (string.equalsIgnoreCase(spectator)) {
return GameMode.SPECTATOR;
} else {
return GameMode.SURVIVAL;
}
}
}

View File

@ -4,10 +4,6 @@ import com.djrapitops.plan.Plan;
import org.bukkit.configuration.ConfigurationSection;
import java.util.*;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public abstract class Database {
@ -48,5 +44,7 @@ public abstract class Database {
public abstract void saveServerData(ServerData serverData);
public abstract ServerData getServerData();
public abstract ServerData getNewestServerData();
public abstract void close();
}

View File

@ -15,7 +15,7 @@ public class DemographicsData {
}
public DemographicsData() {
this(-1, Gender.UNKNOWN, "UNKNOWN");
this(-1, Gender.UNKNOWN, "Not_known");
}
// Getters

View File

@ -1,13 +1,12 @@
package com.djrapitops.plan.database;
import com.djrapitops.plan.database.DemographicsData;
import com.djrapitops.plan.database.Database;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
@ -38,6 +37,9 @@ public class UserData {
public UserData(Player player, DemographicsData demData, Database db) {
uuid = player.getUniqueId();
bedLocation = player.getBedSpawnLocation();
if (bedLocation == null) {
bedLocation = new Location(Bukkit.getServer().getWorlds().get(0), 0, 0 ,0);
}
registered = player.getFirstPlayed();
location = player.getLocation();
isOp = player.isOp();
@ -45,6 +47,12 @@ public class UserData {
nicknames = new ArrayList<>();
ips = new ArrayList<>();
gmTimes = new HashMap<>();
long zero = Long.parseLong("0");
gmTimes.put(GameMode.SURVIVAL, zero);
gmTimes.put(GameMode.CREATIVE, zero);
gmTimes.put(GameMode.ADVENTURE, zero);
gmTimes.put(GameMode.SPECTATOR, zero);
lastGamemode = player.getGameMode();
this.demData = demData;
isBanned = player.isBanned();
}
@ -52,24 +60,20 @@ public class UserData {
public UserData(OfflinePlayer player, DemographicsData demData, Database db) {
uuid = player.getUniqueId();
bedLocation = player.getBedSpawnLocation();
if (bedLocation == null) {
bedLocation = new Location(Bukkit.getServer().getWorlds().get(0), 0, 0 ,0);
}
registered = player.getFirstPlayed();
isOp = player.isOp();
locations = new ArrayList<>();
nicknames = new ArrayList<>();
ips = new ArrayList<>();
gmTimes = new HashMap<>();
this.demData = demData;
isBanned = player.isBanned();
}
public UserData(OfflinePlayer player, DemographicsData demData) {
uuid = player.getUniqueId();
bedLocation = player.getBedSpawnLocation();
registered = player.getFirstPlayed();
isOp = player.isOp();
locations = new ArrayList<>();
nicknames = new ArrayList<>();
ips = new ArrayList<>();
gmTimes = new HashMap<>();
long zero = Long.parseLong("0");
gmTimes.put(GameMode.SURVIVAL, zero);
gmTimes.put(GameMode.CREATIVE, zero);
gmTimes.put(GameMode.ADVENTURE, zero);
gmTimes.put(GameMode.SPECTATOR, zero);
this.demData = demData;
isBanned = player.isBanned();
}
@ -86,12 +90,12 @@ public class UserData {
public void addLocation(Location loc) {
locations.add(loc);
location = locations.get(locations.size()-1);
location = locations.get(locations.size() - 1);
}
public void addLocations(Collection<Location> addLocs) {
locations.addAll(addLocs);
location = locations.get(locations.size()-1);
location = locations.get(locations.size() - 1);
}
public void addNickname(String nick) {

View File

@ -2,6 +2,7 @@ package com.djrapitops.plan.database.databases;
import com.djrapitops.plan.Plan;
import com.djrapitops.plan.api.Gender;
import com.djrapitops.plan.command.utils.MiscUtils;
import com.djrapitops.plan.database.Database;
import com.djrapitops.plan.database.DemographicsData;
import com.djrapitops.plan.database.ServerData;
@ -13,13 +14,18 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import static org.bukkit.Bukkit.getOfflinePlayer;
import org.bukkit.GameMode;
import org.bukkit.Location;
import static org.bukkit.Bukkit.getOfflinePlayer;
public abstract class SQLDB extends Database {
@ -149,7 +155,7 @@ public abstract class SQLDB extends Database {
set.close();
query("CREATE TABLE IF NOT EXISTS " + userName + " ("
+ userColumnID + " int NOT NULL PRIMARY KEY, "
+ userColumnID + " int PRIMARY KEY, "
+ userColumnUUID + " varchar(36) NOT NULL, "
+ userColumnDemAge + " int NOT NULL, "
+ userColumnDemGender + " varchar(8) NOT NULL, "
@ -226,6 +232,7 @@ public abstract class SQLDB extends Database {
return connection.createStatement().execute(sql);
}
@Override
public void close() {
try {
if (connection != null) {
@ -281,14 +288,14 @@ public abstract class SQLDB extends Database {
int userId = -1;
try {
PreparedStatement statement = connection.prepareStatement("SELECT "+userColumnID+" FROM " + userName + " WHERE UPPER(" + userColumnUUID + ") LIKE UPPER(?)");
PreparedStatement statement = connection.prepareStatement("SELECT " + userColumnID + " FROM " + userName + " WHERE UPPER(" + userColumnUUID + ") LIKE UPPER(?)");
statement.setString(1, uuid);
ResultSet set = statement.executeQuery();
while (set.next()) {
userId = set.getInt(userColumnID);
userId = set.getInt(userColumnID);
}
set.close();
} catch (SQLException | NullPointerException e) {
} catch (SQLException e) {
e.printStackTrace();
}
return userId;
@ -299,78 +306,96 @@ public abstract class SQLDB extends Database {
checkConnection();
try {
PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + userName + " WHERE UPPER(" + userColumnUUID + ") LIKE UPPER(?)");
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
UserData data = new UserData(getOfflinePlayer(uuid), new DemographicsData(), this);
if (wasSeenBefore(uuid)) {
PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + userName + " WHERE UPPER(" + userColumnUUID + ") LIKE UPPER(?)");
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
UserData data = new UserData(getOfflinePlayer(uuid), new DemographicsData());
String id = null;
while (set.next()) {
id = set.getString(userColumnID);
if (id == null) {
return null;
String id = null;
while (set.next()) {
id = set.getString(userColumnID);
if (id == null) {
return null;
}
data.getDemData().setAge(set.getInt(userColumnDemAge));
data.getDemData().setGender(Gender.parse(set.getString(userColumnDemGender)));
data.getDemData().setGeoLocation(set.getString(userColumnDemGeoLocation));
data.setLastGamemode(MiscUtils.parseGM(set.getString(userColumnLastGM)));
data.setLastGmSwapTime(set.getLong(userColumnLastGMSwapTime));
data.setPlayTime(set.getLong(userColumnPlayTime));
}
data.getDemData().setAge(set.getInt(userColumnDemAge));
data.getDemData().setGender(Gender.parse(set.getString(userColumnDemGender)));
data.getDemData().setGeoLocation(set.getString(userColumnDemGeoLocation));
data.setLastGamemode(GameMode.valueOf(userColumnLastGM));
data.setLastGmSwapTime(set.getLong(userColumnLastGMSwapTime));
data.setPlayTime(set.getLong(userColumnPlayTime));
}
set.close();
set.close();
statement.close();
statement = connection.prepareStatement("SELECT * FROM " + locationName + " WHERE UPPER(" + locationColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, id);
set = statement.executeQuery();
statement = connection.prepareStatement("SELECT * FROM " + locationName + " WHERE UPPER(" + locationColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, id);
set = statement.executeQuery();
List<Location> locations = new ArrayList<>();
while (set.next()) {
locations.add(new Location(Bukkit.getWorld(set.getString(locationColumnWorld)), set.getInt(locationColumnCoordinatesX), 0, set.getInt(locationColumnCoordinatesZ)));
}
set.close();
data.addLocations(locations);
if (locations.isEmpty()) {
plugin.logToFile("DATABASE-SQLDB\nLocations list is empty");
List<Location> locations = new ArrayList<>();
while (set.next()) {
locations.add(new Location(Bukkit.getWorld(set.getString(locationColumnWorld)), set.getInt(locationColumnCoordinatesX), 0, set.getInt(locationColumnCoordinatesZ)));
}
set.close();
statement.close();
data.addLocations(locations);
if (locations.isEmpty()) {
plugin.logToFile("DATABASE-SQLDB\nLocations list is empty");
} else {
data.setLocation(locations.get(locations.size() - 1));
}
statement = connection.prepareStatement("SELECT * FROM " + nicknamesName + " WHERE UPPER(" + nicknamesColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, id);
set = statement.executeQuery();
List<String> nicknames = new ArrayList<>();
while (set.next()) {
nicknames.add(set.getString(nicknamesColumnNick));
}
set.close();
statement.close();
data.addNicknames(nicknames);
statement = connection.prepareStatement("SELECT * FROM " + ipsName + " WHERE UPPER(" + ipsColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, id);
set = statement.executeQuery();
List<InetAddress> ips = new ArrayList<>();
while (set.next()) {
try {
ips.add(InetAddress.getByName(set.getString(ipsColumnIP)));
} catch (SQLException | UnknownHostException e) {
}
}
set.close();
statement.close();
data.addIpAddresses(ips);
statement = connection.prepareStatement("SELECT * FROM " + gamemodetimesName + " WHERE UPPER(" + gamemodetimesColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, id);
set = statement.executeQuery();
HashMap<GameMode, Long> times = new HashMap<>();
while (set.next()) {
times.put(GameMode.valueOf(set.getString(gamemodetimesColumnGamemode)), set.getLong(gamemodetimesColumnTime));
}
set.close();
statement.close();
data.setGmTimes(times);
} else {
data.setLocation(locations.get(locations.size() - 1));
}
statement = connection.prepareStatement("SELECT * FROM " + nicknamesName + " WHERE UPPER(" + nicknamesColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, id);
set = statement.executeQuery();
List<String> nicknames = new ArrayList<>();
while (set.next()) {
nicknames.add(set.getString(nicknamesColumnNick));
}
set.close();
data.addNicknames(nicknames);
statement = connection.prepareStatement("SELECT * FROM " + ipsName + " WHERE UPPER(" + ipsColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, id);
set = statement.executeQuery();
List<InetAddress> ips = new ArrayList<>();
while (set.next()) {
try {
ips.add(InetAddress.getByName(set.getString(ipsColumnIP)));
} catch (SQLException | UnknownHostException e) {
GameMode defaultGM = Bukkit.getServer().getDefaultGameMode();
if (defaultGM != null) {
data.setLastGamemode(defaultGM);
} else {
data.setLastGamemode(GameMode.SURVIVAL);
}
data.setPlayTime(Long.parseLong("0"));
data.setTimesKicked(0);
data.setLoginTimes(1);
data.setLastGmSwapTime(Long.parseLong("0"));
}
set.close();
data.addIpAddresses(ips);
statement = connection.prepareStatement("SELECT * FROM " + gamemodetimesName + " WHERE UPPER(" + gamemodetimesColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, id);
set = statement.executeQuery();
HashMap<GameMode, Long> times = new HashMap<>();
while (set.next()) {
times.put(GameMode.valueOf(set.getString(gamemodetimesColumnGamemode)), set.getLong(gamemodetimesColumnTime));
}
set.close();
data.setGmTimes(times);
return data;
} catch (SQLException e) {
plugin.logToFile("DATABASE-SQLDB\n" + e + "\n" + e.getCause());
@ -379,29 +404,50 @@ public abstract class SQLDB extends Database {
}
@Override
public ServerData getServerData() {
public ServerData getNewestServerData() {
HashMap<String, Integer> commandUse = getCommandUse();
int newPlayers = 0;
try{
Date now = new Date();
Date startOfToday = new Date(now.getTime() - now.getTime() % 86400000);
try {
PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + serverdataName
+"ORDER BY "+serverdataColumnDate+" ASC LIMIT 1");
+ "ORDER BY " + serverdataColumnDate + " ASC");
ResultSet set = statement.executeQuery();
while (set.next()) {
newPlayers = set.getInt(serverdataColumnNewPlayers);
Date lastSave = new Date(set.getLong(serverdataColumnDate));
Date startOfSaveDay = new Date(lastSave.getTime() - lastSave.getTime() % 86400000);
if (startOfSaveDay == startOfToday) {
newPlayers = set.getInt(serverdataColumnNewPlayers);
}
}
set.close();
statement.close();
} catch (SQLException e) {
plugin.logToFile("DATABASE-SQLDB-GetServerData\n" + e + "\n" + e.getCause());
return null;
}
return new ServerData(commandUse, newPlayers);
}
@Override
public void saveServerData(ServerData data) {
saveCommandUse(data.getCommandUsage());
try {
saveCommandUse(data.getCommandUsage());
long now = new Date().getTime();
PreparedStatement statement = connection.prepareStatement("INSERT INTO " + serverdataName + " ("
+ serverdataColumnDate + ", "
+ serverdataColumnNewPlayers + ", "
+ serverdataColumnPlayersOnline
+ ") VALUES (?, ?, ?)");
statement.setLong(1, now);
statement.setInt(2, data.getNewPlayers());
statement.setInt(3, data.getPlayersOnline());
statement.execute();
statement.close();
} catch (SQLException ex) {
Logger.getLogger(SQLDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void saveCommandUse(HashMap<String, Integer> data) {
@ -409,7 +455,7 @@ public abstract class SQLDB extends Database {
PreparedStatement statement = connection.prepareStatement(
"DELETE FROM " + commanduseName);
statement.execute();
statement.close();
for (String key : data.keySet()) {
statement = connection.prepareStatement("INSERT INTO " + commanduseName + " ("
+ commanduseColumnCommand + ", "
@ -419,6 +465,7 @@ public abstract class SQLDB extends Database {
statement.setString(1, key);
statement.setInt(2, data.get(key));
statement.execute();
statement.close();
}
} catch (SQLException e) {
@ -428,7 +475,7 @@ public abstract class SQLDB extends Database {
private HashMap<String, Integer> getCommandUse() {
HashMap<String, Integer> commandUse = new HashMap<>();
try{
try {
PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + commanduseName);
ResultSet set = statement.executeQuery();
@ -437,6 +484,7 @@ public abstract class SQLDB extends Database {
commandUse.put(set.getString(commanduseColumnCommand), set.getInt(commanduseColumnTimesUsed));
}
set.close();
statement.close();
} catch (SQLException e) {
plugin.logToFile("DATABASE-SQLDB\n" + e + "\n" + e.getCause());
}
@ -456,18 +504,23 @@ public abstract class SQLDB extends Database {
statement = connection.prepareStatement("DELETE FROM " + userName + " WHERE UPPER(" + userColumnUUID + ") LIKE UPPER(?)");
statement.setString(1, uuid);
statement.execute();
statement.close();
statement = connection.prepareStatement("DELETE FROM " + locationName + " WHERE UPPER(" + locationColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, "" + userId);
statement.execute();
statement.close();
statement = connection.prepareStatement("DELETE FROM " + nicknamesName + " WHERE UPPER(" + nicknamesColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, "" + userId);
statement.execute();
statement.close();
statement = connection.prepareStatement("DELETE FROM " + gamemodetimesName + " WHERE UPPER(" + gamemodetimesColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, "" + userId);
statement.execute();
statement.close();
statement = connection.prepareStatement("DELETE FROM " + ipsName + " WHERE UPPER(" + ipsColumnIP + ") LIKE UPPER(?)");
statement.setString(1, "" + userId);
statement.execute();
statement.close();
} catch (SQLException e) {
plugin.logToFile("DATABASE_SQLDB\n" + e + "\n" + e.getCause());
}
@ -479,26 +532,31 @@ public abstract class SQLDB extends Database {
int userId = getUserId(uuid.toString());
try {
String sql = "UPDATE " + userName + " SET "
+ userColumnDemAge + "=?, "
+ userColumnDemGender + "=? "
+ userColumnDemGeoLocation + "=? "
+ userColumnLastGM + "=? "
+ userColumnLastGMSwapTime + "=? "
+ userColumnDemGender + "=?, "
+ userColumnDemGeoLocation + "=?, "
+ userColumnLastGM + "=?, "
+ userColumnLastGMSwapTime + "=?, "
+ userColumnPlayTime + "=? "
+ "WHERE UPPER(" + userColumnUUID + ") LIKE UPPER(?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, data.getDemData().getAge());
statement.setString(2, data.getDemData().getGender().toString());
statement.setString(2, data.getDemData().getGender().toString().toLowerCase());
statement.setString(3, data.getDemData().getGeoLocation());
statement.setString(4, data.getLastGamemode().name());
GameMode gm = data.getLastGamemode();
if (gm != null) {
statement.setString(4, data.getLastGamemode().name());
} else {
statement.setString(4, GameMode.SURVIVAL.name());
}
statement.setLong(5, data.getLastGmSwapTime());
statement.setLong(6, data.getPlayTime());
if (statement.executeUpdate() == 0) {
statement = connection.prepareStatement("INSERT INTO " + userName + " ("
+ userColumnID + ", "
+ userColumnUUID + ", "
+ userColumnDemAge + ", "
+ userColumnDemGender + ", "
@ -506,26 +564,35 @@ public abstract class SQLDB extends Database {
+ userColumnLastGM + ", "
+ userColumnLastGMSwapTime + ", "
+ userColumnPlayTime
+ ") VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
+ ") VALUES (?, ?, ?, ?, ?, ?, ?)");
statement.setInt(1, userId);
statement.setString(2, uuid.toString());
statement.setInt(3, data.getDemData().getAge());
statement.setString(4, data.getDemData().getGender().toString());
statement.setString(5, data.getDemData().getGeoLocation());
statement.setString(6, data.getLastGamemode().name());
statement.setLong(7, data.getLastGmSwapTime());
statement.setLong(8, data.getPlayTime());
statement.setString(1, uuid.toString());
statement.setInt(2, data.getDemData().getAge());
statement.setString(3, data.getDemData().getGender().toString().toLowerCase());
statement.setString(4, data.getDemData().getGeoLocation());
if (gm != null) {
statement.setString(5, data.getLastGamemode().name());
} else {
statement.setString(5, GameMode.SURVIVAL.name());
}
statement.setLong(6, data.getLastGmSwapTime());
statement.setLong(7, data.getPlayTime());
statement.execute();
statement.close();
}
saveLocationList(userId, data.getLocations());
saveNickList(userId, data.getNicknames());
saveIPList(userId, data.getIps());
saveGMTimes(userId, data.getGmTimes());
} catch (SQLException e) {
} catch (SQLException | NullPointerException e) {
e.printStackTrace();
plugin.logToFile("SQLDB-Save\n" + e
+ "\n" + data.getLastGamemode()
+ "\n" + Bukkit.getDefaultGameMode()
+ "\n" + wasSeenBefore(uuid)
);
}
}
@ -535,6 +602,7 @@ public abstract class SQLDB extends Database {
"DELETE FROM " + locationName + " WHERE UPPER(" + locationColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, "" + userId);
statement.execute();
statement.close();
for (int i = 0; i < locations.size(); i++) {
Location location = locations.get(i);
@ -553,6 +621,7 @@ public abstract class SQLDB extends Database {
statement.setString(5, location.getWorld().getName());
statement.execute();
statement.close();
}
} catch (SQLException e) {
@ -576,6 +645,7 @@ public abstract class SQLDB extends Database {
statement.setInt(1, userId);
statement.setString(2, name);
statement.execute();
statement.close();
}
} catch (SQLException e) {
@ -589,6 +659,7 @@ public abstract class SQLDB extends Database {
"DELETE FROM " + ipsName + " WHERE UPPER(" + ipsColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, "" + userId);
statement.execute();
statement.close();
for (InetAddress ip : ips) {
statement = connection.prepareStatement("INSERT INTO " + ipsName + " ("
@ -599,6 +670,7 @@ public abstract class SQLDB extends Database {
statement.setInt(1, userId);
statement.setString(2, ip.getHostAddress());
statement.execute();
statement.close();
}
} catch (SQLException e) {
@ -612,6 +684,7 @@ public abstract class SQLDB extends Database {
"DELETE FROM " + gamemodetimesName + " WHERE UPPER(" + gamemodetimesColumnUserID + ") LIKE UPPER(?)");
statement.setString(1, "" + userId);
statement.execute();
statement.close();
for (GameMode gm : gamemodeTimes.keySet()) {
statement = connection.prepareStatement("INSERT INTO " + gamemodetimesName + " ("
@ -624,6 +697,7 @@ public abstract class SQLDB extends Database {
statement.setString(2, gm.name());
statement.setLong(3, gamemodeTimes.get(gm));
statement.execute();
statement.close();
}
} catch (SQLException e) {

View File

@ -24,7 +24,7 @@ public class ActivityHandler {
public void saveToCache(Player player, UserData data) {
long timeNow = new Date().getTime();
data.setPlayTime(data.getPlayTime()+(data.getLastPlayed()-timeNow));
data.setPlayTime(data.getPlayTime() + (data.getLastPlayed() - timeNow));
data.setLastPlayed(timeNow);
}
@ -35,7 +35,12 @@ public class ActivityHandler {
public void handleLogOut(PlayerQuitEvent event, UserData data) {
Player player = event.getPlayer();
data.setPlayTime(data.getPlayTime()+(data.getLastPlayed()-new Date().getTime()));
data.setPlayTime(data.getPlayTime() + (data.getLastPlayed() - new Date().getTime()));
data.setLastPlayed(player.getLastPlayed());
}
void handleReload(Player player, UserData data) {
data.setPlayTime(data.getPlayTime() + (data.getLastPlayed() - new Date().getTime()));
data.setLastPlayed(player.getLastPlayed());
}
}

View File

@ -20,15 +20,14 @@ public class BasicInfoHandler {
}
public void handleLogIn(PlayerLoginEvent event) {
public void handleLogIn(PlayerLoginEvent event, UserData data) {
Player player = event.getPlayer();
UserData data = handler.getCurrentData(player.getUniqueId());
data.addNickname(player.getDisplayName());
data.addIpAddress(event.getAddress());
}
public void handleLogOut(PlayerQuitEvent event) {
Player player = event.getPlayer();
UserData data = handler.getCurrentData(player.getUniqueId());
void handleReload(Player player, UserData data) {
data.addNickname(player.getDisplayName());
data.addIpAddress(player.getAddress().getAddress());
}
}

View File

@ -8,7 +8,11 @@ import com.djrapitops.plan.database.ServerData;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.Bukkit;
import static org.bukkit.Bukkit.getOfflinePlayer;
import org.bukkit.GameMode;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerLoginEvent;
public class DataHandler {
@ -25,6 +29,8 @@ public class DataHandler {
private final PlanLiteHandler planLiteHandler;
private final Database db;
private int timesSaved;
public DataHandler(Plan plugin) {
this.plugin = plugin;
db = plugin.getDB();
@ -35,16 +41,21 @@ public class DataHandler {
demographicsHandler = new DemographicsHandler(plugin, this);
basicInfoHandler = new BasicInfoHandler(plugin, this);
ruleBreakingHandler = new RuleBreakingHandler(plugin, this);
serverData = db.getServerData();
serverData = db.getNewestServerData();
serverDataHandler = new ServerDataHandler(serverData);
planLiteHandler = new PlanLiteHandler(plugin);
timesSaved = 0;
int minutes = plugin.getConfig().getInt("saveEveryXMinutes");
plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
@Override
public void run() {
saveHandlerDataToCache();
saveCachedData();
if (timesSaved % 5 == 0) {
clearCache();
}
}
}, 60 * 20 * minutes, 60 * 20 * minutes);
}
@ -55,9 +66,6 @@ public class DataHandler {
}
public UserData getCurrentData(UUID uuid, boolean cache) {
if (!db.wasSeenBefore(uuid)) {
return null;
}
if (cache) {
if (dataCache.get(uuid) == null) {
dataCache.put(uuid, db.getUserData(uuid));
@ -77,16 +85,36 @@ public class DataHandler {
saveCachedData(uuid);
});
saveServerData();
timesSaved++;
}
public void saveCacheOnDisable() {
dataCache.keySet().stream().forEach((uuid) -> {
if (dataCache.get(uuid) != null) {
db.saveUserData(uuid, dataCache.get(uuid));
}
});
db.saveServerData(serverData);
}
public void saveCachedData(UUID uuid) {
if (dataCache.get(uuid) != null) {
db.saveUserData(uuid, dataCache.get(uuid));
}
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
if (dataCache.get(uuid) != null) {
db.saveUserData(uuid, dataCache.get(uuid));
}
}
});
}
public void saveServerData() {
db.saveServerData(serverData);
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
db.saveServerData(serverData);
}
});
}
private void saveHandlerDataToCache() {
@ -108,7 +136,19 @@ public class DataHandler {
}
public void newPlayer(Player player) {
dataCache.put(player.getUniqueId(), new UserData(player, new DemographicsData(), db));
UserData data = new UserData(player, new DemographicsData(), db);
saveCachedData(player.getUniqueId());
GameMode defaultGM = Bukkit.getServer().getDefaultGameMode();
if (defaultGM != null) {
data.setLastGamemode(defaultGM);
} else {
data.setLastGamemode(GameMode.SURVIVAL);
}
data.setPlayTime(Long.parseLong("0"));
data.setTimesKicked(0);
data.setLoginTimes(1);
data.setLastGmSwapTime(Long.parseLong("0"));
dataCache.put(player.getUniqueId(), data);
}
public ActivityHandler getActivityHandler() {
@ -135,7 +175,6 @@ public class DataHandler {
return gamemodeTimesHandler;
}
public Database getDB() {
return db;
}
@ -147,4 +186,19 @@ public class DataHandler {
public ServerDataHandler getServerDataHandler() {
return serverDataHandler;
}
public void handleReload() {
for (Player player : Bukkit.getOnlinePlayers()) {
UUID uuid = player.getUniqueId();
boolean newPlayer = activityHandler.isFirstTimeJoin(uuid);
newPlayer(player);
serverDataHandler.handleLogin(newPlayer);
UserData data = getCurrentData(uuid);
activityHandler.handleReload(player, data);
basicInfoHandler.handleReload(player, data);
gamemodeTimesHandler.handleReload(player, data);
demographicsHandler.handleReload(player, data);
saveCachedData(uuid);
}
}
}

View File

@ -1,4 +1,3 @@
package com.djrapitops.plan.datahandlers;
import com.djrapitops.plan.Plan;
@ -17,6 +16,7 @@ import org.bukkit.event.player.PlayerLoginEvent;
import static org.bukkit.plugin.java.JavaPlugin.getPlugin;
public class DemographicsHandler {
private final DataHandler handler;
public DemographicsHandler(Plan plugin, DataHandler h) {
@ -103,23 +103,43 @@ public class DemographicsHandler {
public void handleLogIn(PlayerLoginEvent event, UserData data) {
InetAddress address = event.getAddress();
try {
Scanner locationScanner = new Scanner("http://ip-api.com/line/" + address.getHostAddress());
List<String> results = new ArrayList<>();
while (locationScanner.hasNextLine()) {
results.add(locationScanner.nextLine());
}
if (results.size() >= 2) {
data.getDemData().setGeoLocation(results.get(1));
} else {
data.getDemData().setGeoLocation("UNKOWN");
}
} catch (Exception e) {
Plan plugin = getPlugin(Plan.class);
plugin.logToFile("http://ip-api.com/line/" + address.getHostAddress());
plugin.logToFile("" + e);
plugin.logToFile(address.toString());
Scanner locationScanner = new Scanner("http://ip-api.com/line/" + address.getHostAddress());
List<String> results = new ArrayList<>();
while (locationScanner.hasNextLine()) {
results.add(locationScanner.nextLine());
}
if (results.size() >= 2) {
data.getDemData().setGeoLocation(results.get(1));
} else {
data.getDemData().setGeoLocation("Not Known");
}
} catch (Exception e) {
Plan plugin = getPlugin(Plan.class);
plugin.logToFile("http://ip-api.com/line/" + address.getHostAddress());
plugin.logToFile("" + e);
plugin.logToFile(address.toString());
}
}
void handleReload(Player player, UserData data) {
InetAddress address = player.getAddress().getAddress();
try {
Scanner locationScanner = new Scanner("http://ip-api.com/line/" + address.getHostAddress());
List<String> results = new ArrayList<>();
while (locationScanner.hasNextLine()) {
results.add(locationScanner.nextLine());
}
if (results.size() >= 2) {
data.getDemData().setGeoLocation(results.get(1));
} else {
data.getDemData().setGeoLocation("Not Known");
}
} catch (Exception e) {
Plan plugin = getPlugin(Plan.class);
plugin.logToFile("http://ip-api.com/line/" + address.getHostAddress());
plugin.logToFile("" + e);
plugin.logToFile(address.toString());
}
}
}

View File

@ -1,4 +1,3 @@
package com.djrapitops.plan.datahandlers;
import com.djrapitops.plan.Plan;
@ -7,8 +6,10 @@ import java.util.HashMap;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerLoginEvent;
public class GamemodeTimesHandler {
private final Plan plugin;
private final DataHandler handler;
@ -17,13 +18,17 @@ public class GamemodeTimesHandler {
handler = h;
}
public void handleLogin(PlayerLoginEvent event, UserData data) {
data.setLastGamemode(event.getPlayer().getGameMode());
}
public void handleChangeEvent(PlayerGameModeChangeEvent event, UserData data) {
HashMap<GameMode, Long> times = data.getGmTimes();
long lastSwap = data.getLastGmSwapTime();
handler.getActivityHandler().saveToCache(event.getPlayer(), data);
long now = data.getPlayTime();
GameMode oldGM = data.getLastGamemode();
data.setGMTime(oldGM, times.get(oldGM)+(lastSwap-now));
data.setGMTime(oldGM, times.get(oldGM) + (lastSwap - now));
GameMode newGM = event.getNewGameMode();
data.setLastGamemode(newGM);
data.setLastGmSwapTime(now);
@ -35,9 +40,18 @@ public class GamemodeTimesHandler {
handler.getActivityHandler().saveToCache(p, data);
long now = data.getPlayTime();
GameMode currentGM = p.getGameMode();
data.setGMTime(currentGM, times.get(currentGM)+(lastSwap-now));
data.setGMTime(currentGM, times.get(currentGM) + (lastSwap - now));
data.setLastGmSwapTime(now);
}
void handleReload(Player p, UserData data) {
HashMap<GameMode, Long> times = data.getGmTimes();
long lastSwap = data.getLastGmSwapTime();
handler.getActivityHandler().saveToCache(p, data);
long now = data.getPlayTime();
GameMode currentGM = p.getGameMode();
data.setGMTime(currentGM, times.get(currentGM) + (lastSwap - now));
data.setLastGmSwapTime(now);
}
}

View File

@ -0,0 +1,30 @@
package com.djrapitops.plan.datahandlers.listeners;
import com.djrapitops.plan.Plan;
import com.djrapitops.plan.datahandlers.DataHandler;
import com.djrapitops.plan.datahandlers.ServerDataHandler;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class PlanCommandPreprocessListener implements Listener {
private final Plan plugin;
private final DataHandler handler;
private final ServerDataHandler serverH;
public PlanCommandPreprocessListener(Plan plugin) {
this.plugin = plugin;
handler = plugin.getHandler();
serverH = handler.getServerDataHandler();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
if (event.isCancelled()) {
return;
}
serverH.handleCommand(event.getMessage().split("\\s*")[0]);
}
}

View File

@ -8,6 +8,8 @@ import com.djrapitops.plan.datahandlers.LocationHandler;
import com.djrapitops.plan.datahandlers.RuleBreakingHandler;
import com.djrapitops.plan.datahandlers.ServerDataHandler;
import com.djrapitops.plan.database.UserData;
import com.djrapitops.plan.datahandlers.BasicInfoHandler;
import com.djrapitops.plan.datahandlers.GamemodeTimesHandler;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@ -22,6 +24,8 @@ public class PlanPlayerListener implements Listener {
private final DataHandler handler;
private final ActivityHandler activityH;
private final BasicInfoHandler basicInfoH;
private final GamemodeTimesHandler gmTimesH;
private final LocationHandler locationH;
private final DemographicsHandler demographicH;
private final RuleBreakingHandler rulebreakH;
@ -30,6 +34,8 @@ public class PlanPlayerListener implements Listener {
public PlanPlayerListener(Plan plugin) {
handler = plugin.getHandler();
activityH = handler.getActivityHandler();
basicInfoH = handler.getBasicInfoHandler();
gmTimesH = handler.getGamemodeTimesHandler();
demographicH = handler.getDemographicsHandler();
locationH = handler.getLocationHandler();
rulebreakH = handler.getRuleBreakingHandler();
@ -44,12 +50,12 @@ public class PlanPlayerListener implements Listener {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
boolean newPlayer = activityH.isFirstTimeJoin(uuid);
if (newPlayer) {
handler.newPlayer(player);
}
handler.newPlayer(player);
serverHandler.handleLogin(newPlayer);
UserData data = handler.getCurrentData(uuid);
activityH.handleLogIn(event, data);
basicInfoH.handleLogIn(event, data);
gmTimesH.handleLogin(event, data);
demographicH.handleLogIn(event, data);
handler.saveCachedData(uuid);
}

View File

@ -0,0 +1,38 @@
package com.djrapitops.plan.datahandlers.listeners;
import com.djrapitops.plan.Plan;
import com.djrapitops.plan.datahandlers.DataHandler;
import com.djrapitops.plan.datahandlers.LocationHandler;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
public class PlanPlayerMoveListener implements Listener {
private final Plan plugin;
private final DataHandler handler;
private final LocationHandler locationH;
public PlanPlayerMoveListener(Plan plugin) {
this.plugin = plugin;
handler = plugin.getHandler();
locationH = handler.getLocationHandler();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerMove(PlayerMoveEvent event) {
if (event.isCancelled()) {
return;
}
Player p = event.getPlayer();
Location from = event.getFrom();
Location to = event.getTo();
if (from.getBlockX() == to.getBlockX() && from.getBlockZ() == to.getBlockZ() && from.getWorld() == to.getWorld()) {
return;
}
locationH.addLocation(p.getUniqueId(), to);
}
}