Merge branch '4.0.0-BungeeCord-Support' of https://github.com/Rsl1122/Plan-PlayerAnalytics

# Conflicts:
#	Plan/src/main/java/com/djrapitops/plan/data/listeners/PlanPlayerListener.java
#	Plan/src/main/java/com/djrapitops/plan/database/Database.java
#	Plan/src/main/java/com/djrapitops/plan/database/databases/SQLDB.java
#	Plan/src/main/java/com/djrapitops/plan/database/tables/KillsTable.java
#	Plan/src/main/java/com/djrapitops/plan/database/tables/NicknamesTable.java
#	Plan/src/main/java/com/djrapitops/plan/database/tables/SessionsTable.java
#	Plan/src/main/java/com/djrapitops/plan/database/tables/UsersTable.java
#	Plan/src/main/java/com/djrapitops/plan/database/tables/WorldTimesTable.java
This commit is contained in:
Fuzzlemann 2017-08-23 14:11:08 +02:00
commit 2df6169dd9
40 changed files with 1038 additions and 1287 deletions

View File

@ -54,8 +54,6 @@ import org.bukkit.ChatColor;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
/**
* Main class for Bukkit that manages the plugin.
@ -263,18 +261,11 @@ public class Plan extends BukkitPlugin<Plan> {
getServer().getScheduler().cancelTasks(this);
if (Verify.notNull(dataCache, db)) {
Benchmark.start("Disable: DataCache Save");
// Saves the DataCache to the database without Bukkit's Schedulers.
Log.info(Locale.get(Msg.DISABLE_CACHE_SAVE).toString());
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.execute(() -> {
dataCache.saveCacheOnDisable();
taskStatus().cancelAllKnownTasks();
Benchmark.stop("Disable: DataCache Save");
});
scheduler.shutdown(); // Schedules the save to shutdown after it has ran the execute method.
// TODO Process all leftover Processors.
taskStatus().cancelAllKnownTasks();
}
getPluginLogger().endAllDebugs();

View File

@ -85,7 +85,7 @@ public class ManageRemoveCommand extends SubCommand {
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_START).parse());
try {
// TODO Clear active session of user & start new one
if (plugin.getDB().removeAccount(uuid.toString())) {
if (plugin.getDB().removeAccount(uuid)) {
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_REMOVE_SUCCESS).parse(playerName, plugin.getDB().getConfigName()));
} else {
sender.sendMessage(Locale.get(Msg.MANAGE_INFO_FAIL).toString());

View File

@ -3,6 +3,7 @@ package main.java.com.djrapitops.plan.data;
import main.java.com.djrapitops.plan.data.time.WorldTimes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
@ -57,8 +58,8 @@ public class Session {
this.sessionID = id;
this.sessionStart = sessionStart;
this.sessionEnd = sessionEnd;
this.worldTimes = worldTimes;
this.playerKills = playerKills;
this.worldTimes = new WorldTimes(new HashMap<>());
this.playerKills = new ArrayList<>();
this.mobKills = mobKills;
this.deaths = deaths;
}
@ -197,4 +198,8 @@ public class Session {
public long getSessionID() {
return sessionID;
}
public void setSessionID(long sessionID) {
this.sessionID = sessionID;
}
}

View File

@ -1,21 +1,19 @@
package main.java.com.djrapitops.plan.data.cache;
import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.player.IPlayer;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.queue.processing.Processor;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import org.bukkit.entity.Player;
import java.sql.SQLException;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This Class contains the Cache.
@ -30,8 +28,6 @@ import java.util.*;
*/
public class DataCache extends SessionCache {
// Plan
private final Plan plugin;
private final Database db;
//Cache
@ -53,9 +49,7 @@ public class DataCache extends SessionCache {
* @param plugin Current instance of Plan
*/
public DataCache(Plan plugin) {
super(); // Initializes Session & Location cache.
this.plugin = plugin;
super(plugin); // Initializes Session & Location cache.
db = plugin.getDB();
commandUse = new HashMap<>();
@ -115,47 +109,6 @@ public class DataCache extends SessionCache {
}).runTaskTimerAsynchronously(60L * 20L * 5, 60L * 20L * 5);
}
/**
* Saves all data in the cache to Database and closes the database down.
* <p>
* Stops all tasks.
* <p>
* If processingQueue has unprocessed information, it will be processed.
*/
@Deprecated
public void saveCacheOnDisable() { // TODO Rewrite
long time = MiscUtils.getTime();
Benchmark.start("Cache: SaveOnDisable");
Benchmark.start("Cache: ProcessOnlineHandlingInfo");
List<IPlayer> onlinePlayers = plugin.fetch().getOnlinePlayers();
Log.debug("Online: " + onlinePlayers.size());
for (IPlayer p : onlinePlayers) {
UUID uuid = p.getUuid();
endSession(uuid);
String worldName = ((Player) p.getWrappedPlayerClass()).getWorld().getName();
}
Benchmark.stop("Cache: ProcessOnlineHandlingInfo");
try {
db.saveCommandUse(commandUse);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
saveUnsavedTPSHistory();
try {
db.close();
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
Benchmark.stop("Cache: SaveOnDisable");
}
private void processUnprocessedHandlingInfo(List<Processor> toProcess) {
Log.debug("PROCESS: " + toProcess.size());
for (Processor i : toProcess) {
i.process();
}
}
/**
* Saves the cached CommandUse.
* <p>

View File

@ -1,7 +1,10 @@
package main.java.com.djrapitops.plan.data.cache;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.Session;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@ -16,11 +19,13 @@ import java.util.UUID;
public class SessionCache {
private static final Map<UUID, Session> activeSessions = new HashMap<>();
protected final Plan plugin;
/**
* Class Constructor.
*/
public SessionCache() {
public SessionCache(Plan plugin) {
this.plugin = plugin;
}
public void cacheSession(UUID uuid, Session session) {
@ -33,25 +38,11 @@ public class SessionCache {
return;
}
session.endSession(time);
// TODO DB Save the session.
}
/**
* Starts a session for a player at the current moment.
*
* @param uuid UUID of the player.
*/
@Deprecated
public void startSession(UUID uuid) {
}
/**
* Ends a session for a player at the current moment.
*
* @param uuid UUID of the player.
*/
@Deprecated
public void endSession(UUID uuid) {
try {
plugin.getDB().getSessionsTable().saveSession(uuid, session);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
}
/**

View File

@ -1,57 +0,0 @@
package main.java.com.djrapitops.plan.data.handling;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import java.sql.SQLException;
import java.util.UUID;
/**
* Class containing static methods for processing information contained in a
* DeathEvent when the killer is a player.
*
* @author Rsl1122
* @since 3.0.0
*/
public class KillHandling {
/**
* Utility Class, hides constructor.
*/
private KillHandling() {
throw new IllegalStateException("Utility Class.");
}
/**
* Processes the information of the Event and changes UserData object
* accordingly.
*
* @param data UserData of the player.
* @param time Epoch ms the event occurred.
* @param dead Mob or a Player the player killed.
* @param weaponName The name of the Weapon used.
*/
public static void processKillInfo(UserData data, long time, LivingEntity dead, String weaponName) {
Plan plugin = Plan.getInstance();
if (dead instanceof Player) {
Player deadPlayer = (Player) dead;
int victimID;
try {
UUID victimUUID = deadPlayer.getUniqueId();
victimID = plugin.getDB().getUsersTable().getUserId(victimUUID);
if (victimID == -1) {
return;
}
//TODO Move to Session data.addPlayerKill(new KillData(victimUUID, victimID, weaponName, time));
} catch (SQLException e) {
Log.toLog("main.java.com.djrapitops.plan.KillHandling", e);
}
} else {
//TODO Move to Session data.setMobKills(data.getMobKills() + 1);
}
}
}

View File

@ -0,0 +1,38 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.data.handling.player;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.Action;
import main.java.com.djrapitops.plan.database.tables.Actions;
import java.sql.SQLException;
import java.util.UUID;
/**
* Processor for inserting a FIRST_LOGOUT Action.
*
* @author Rsl1122
* @since 4.0.0
*/
public class FirstLeaveProcessor extends PlayerProcessor {
private final Action leaveAction;
public FirstLeaveProcessor(UUID uuid, long time, int messagesSent) {
super(uuid);
leaveAction = new Action(time, Actions.FIRST_LOGOUT, "Messages sent: " + messagesSent);
}
@Override
public void process() {
try {
Plan.getInstance().getDB().getActionsTable().insertAction(getUUID(), leaveAction);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
}
}

View File

@ -4,8 +4,11 @@
*/
package main.java.com.djrapitops.plan.data.handling.player;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.cache.GeolocationCacheHandler;
import java.sql.SQLException;
import java.util.UUID;
/**
@ -26,6 +29,10 @@ public class IPUpdateProcessor extends PlayerProcessor {
public void process() {
UUID uuid = getUUID();
String country = GeolocationCacheHandler.getCountry(ip);
// TODO DB Update IP & Geolocation
try {
Plan.getInstance().getDB().getIpsTable().updateIP(uuid, ip, country);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
}
}

View File

@ -4,6 +4,10 @@
*/
package main.java.com.djrapitops.plan.data.handling.player;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import java.sql.SQLException;
import java.util.UUID;
/**
@ -19,6 +23,10 @@ public class KickProcessor extends PlayerProcessor {
@Override
public void process() {
UUID uuid = getUUID();
// TODO Update DB Kick +1
try {
Plan.getInstance().getDB().getUsersTable().kicked(uuid);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
}
}

View File

@ -4,6 +4,11 @@
*/
package main.java.com.djrapitops.plan.data.handling.player;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.Database;
import java.sql.SQLException;
import java.util.UUID;
/**
@ -25,6 +30,12 @@ public class NameProcessor extends PlayerProcessor {
@Override
public void process() {
UUID uuid = getUUID();
// TODO DB Update Name & Nicknames.
Database db = Plan.getInstance().getDB();
try {
db.getUsersTable().updateName(uuid, playerName);
db.getNicknamesTable().saveUserName(uuid, displayName);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
}
}

View File

@ -0,0 +1,28 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.data.handling.player;
import java.util.UUID;
/**
* //TODO Class Javadoc Comment
*
* @author Rsl1122
*/
public class OPProcessor extends PlayerProcessor {
private final boolean banned;
public OPProcessor(UUID uuid, boolean banned) {
super(uuid);
this.banned = banned;
}
@Override
public void process() {
UUID uuid = getUUID();
// TODO DB Update Ban status
}
}

View File

@ -4,8 +4,14 @@
*/
package main.java.com.djrapitops.plan.data.handling.player;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.Action;
import main.java.com.djrapitops.plan.data.listeners.PlanPlayerListener;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.database.tables.Actions;
import java.sql.SQLException;
import java.util.UUID;
/**
@ -17,19 +23,31 @@ public class RegisterProcessor extends PlayerProcessor {
private final long time;
private final int playersOnline;
private final String name;
public RegisterProcessor(UUID uuid, long time, int playersOnline) {
private final PlanPlayerListener listener;
public RegisterProcessor(PlanPlayerListener listener, UUID uuid, long time, String name, int playersOnline) {
super(uuid);
this.listener = listener;
this.time = time;
this.playersOnline = playersOnline;
this.name = name;
}
@Override
public void process() {
UUID uuid = getUUID();
if (Plan.getInstance().getDB().wasSeenBefore(uuid)) {
Database db = Plan.getInstance().getDB();
if (db.wasSeenBefore(uuid)) {
return;
}
// TODO DB Register
listener.addFirstLeaveCheck(uuid);
try {
db.getUsersTable().registerUser(uuid, time, name);
db.getActionsTable().insertAction(uuid, new Action(time, Actions.REGISTERED, "Online: " + playersOnline + " Players"));
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
}
}

View File

@ -38,6 +38,7 @@ public class PlanChatListener implements Listener {
}
Player p = event.getPlayer();
// TODO NameCache to DataCache
plugin.addToProcessQueue(new NameProcessor(p.getUniqueId(), p.getName(), p.getDisplayName()));
}
}

View File

@ -15,6 +15,8 @@ import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
@ -28,6 +30,8 @@ public class PlanPlayerListener implements Listener {
private final Plan plugin;
private final DataCache cache;
private final Set<UUID> playersWithFirstSession;
/**
* Class Constructor.
*
@ -36,6 +40,7 @@ public class PlanPlayerListener implements Listener {
public PlanPlayerListener(Plan plugin) {
this.plugin = plugin;
cache = plugin.getDataCache();
playersWithFirstSession = new HashSet<>();
}
@EventHandler(priority = EventPriority.MONITOR)
@ -94,9 +99,9 @@ public class PlanPlayerListener implements Listener {
cache.cacheSession(uuid, Session.start(time, world, gm));
plugin.addToProcessQueue(
new RegisterProcessor(uuid, time, playersOnline), //TODO Add required variables after UsersTable is done.
new RegisterProcessor(this, uuid, time, playerName, playersOnline),
new IPUpdateProcessor(uuid, ip),
new NameProcessor(uuid, playerName, displayName)
new NameProcessor(uuid, playerName, displayName) // TODO NameCache to DataCache
);
}
@ -118,5 +123,16 @@ public class PlanPlayerListener implements Listener {
new BanProcessor(uuid, player.isBanned()),
new EndSessionProcessor(uuid, time)
);
int messagesSent = 0; // TODO messages Sent on first session
if (playersWithFirstSession.contains(uuid)) {
plugin.addToProcessQueue(new FirstLeaveProcessor(uuid, time, messagesSent));
}
}
// TODO MOVE TO DATACACHE
public void addFirstLeaveCheck(UUID uuid) {
playersWithFirstSession.add(uuid);
}
}

View File

@ -32,7 +32,6 @@ public class GMTimes extends TimeKeeper {
public GMTimes(Map<String, Long> times) {
super(times);
}
public GMTimes() {
super();
}

View File

@ -132,4 +132,8 @@ public class WorldTimes {
public Map<String, GMTimes> getWorldTimes() {
return worldTimes;
}
public void setGMTimesForWorld(String world, GMTimes gmTimes) {
worldTimes.put(world, gmTimes);
}
}

View File

@ -29,6 +29,11 @@ public abstract class Database {
*/
protected UsersTable usersTable;
/**
* Table representing plan_actions in the database.
*/
protected ActionsTable actionsTable;
/**
* Table representing plan_kills in the database.
*/
@ -190,7 +195,7 @@ public abstract class Database {
* @return Success of the removal.
* @throws SQLException If a database error occurs.
*/
public abstract boolean removeAccount(String uuid) throws SQLException;
public abstract boolean removeAccount(UUID uuid) throws SQLException;
/**
* Used to clear all data from the database.
@ -326,6 +331,12 @@ public abstract class Database {
return serverTable;
}
public abstract void commit() throws SQLException;
public ActionsTable getActionsTable() {
return actionsTable;
}
public BasicDataSource getDataSource() {
return dataSource;
}

View File

@ -15,7 +15,7 @@ public class MySQLDB extends SQLDB {
* @param plugin Current instance of Plan
*/
public MySQLDB(Plan plugin) {
super(plugin, true);
super(plugin);
}
/**

View File

@ -11,8 +11,10 @@ import org.apache.commons.dbcp2.BasicDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
/**
* Class containing main logic for different data related save & load functionality.
@ -22,28 +24,28 @@ import java.util.stream.Collectors;
*/
public abstract class SQLDB extends Database {
private final boolean supportsModification;
private final boolean usingMySQL;
/**
* @param plugin
* @param supportsModification
*/
public SQLDB(Plan plugin, boolean supportsModification) {
public SQLDB(Plan plugin) {
super(plugin);
this.supportsModification = supportsModification;
usingMySQL = getName().equals("MySQL");
versionTable = new VersionTable(this, usingMySQL);
serverTable = new ServerTable(this, usingMySQL);
securityTable = new SecurityTable(this, usingMySQL);
commandUseTable = new CommandUseTable(this, usingMySQL);
tpsTable = new TPSTable(this, usingMySQL);
usersTable = new UsersTable(this, usingMySQL);
sessionsTable = new SessionsTable(this, usingMySQL);
killsTable = new KillsTable(this, usingMySQL);
actionsTable = new ActionsTable(this, usingMySQL);
ipsTable = new IPsTable(this, usingMySQL);
nicknamesTable = new NicknamesTable(this, usingMySQL);
commandUseTable = new CommandUseTable(this, usingMySQL);
versionTable = new VersionTable(this, usingMySQL);
tpsTable = new TPSTable(this, usingMySQL);
securityTable = new SecurityTable(this, usingMySQL);
sessionsTable = new SessionsTable(this, usingMySQL);
killsTable = new KillsTable(this, usingMySQL);
worldTable = new WorldTable(this, usingMySQL);
worldTimesTable = new WorldTimesTable(this, usingMySQL);
@ -151,18 +153,23 @@ public abstract class SQLDB extends Database {
return new Table[]{
serverTable, usersTable, ipsTable,
nicknamesTable, sessionsTable, killsTable,
commandUseTable, tpsTable, worldTable,
worldTimesTable, securityTable};
commandUseTable, actionsTable, tpsTable,
worldTable, worldTimesTable, securityTable
};
}
/**
* @return
* Get all tables except securityTable for removal of user data.
*
* @return Tables in the order the data should be removed in.
*/
public Table[] getAllTablesInRemoveOrder() {
return new Table[]{
ipsTable,
nicknamesTable, sessionsTable, killsTable,
worldTimesTable, worldTable, usersTable,
commandUseTable, tpsTable, serverTable};
ipsTable, nicknamesTable, killsTable,
worldTimesTable, sessionsTable, actionsTable,
worldTable, usersTable, commandUseTable,
tpsTable, serverTable
};
}
/**
@ -175,10 +182,7 @@ public abstract class SQLDB extends Database {
*/
@Override
public void close() throws SQLException {
/*if (!dataSource.isClosed()) {
dataSource.close();
}*/
dataSource.close();
setStatus("Closed");
Log.logDebug("Database"); // Log remaining Debug info if present
}
@ -210,7 +214,7 @@ public abstract class SQLDB extends Database {
return false;
}
try {
return usersTable.getUserId(uuid.toString()) != -1;
return usersTable.isRegistered(uuid);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
return false;
@ -219,14 +223,8 @@ public abstract class SQLDB extends Database {
}
}
/**
* @param uuid
* @return
* @throws SQLException
*/
@Override
public boolean removeAccount(String uuid) throws SQLException {
if (uuid == null || uuid.isEmpty()) {
public boolean removeAccount(UUID uuid) throws SQLException {
if (uuid == null) {
return false;
}
try {
@ -238,14 +236,27 @@ public abstract class SQLDB extends Database {
Log.toLog(this.getClass().getName(), e);
return false;
}
int userId = usersTable.getUserId(uuid);
return userId != -1
&& ipsTable.removeUserIPs(userId)
&& nicknamesTable.removeUserNicknames(userId)
&& sessionsTable.removeUserSessions(userId)
&& killsTable.removeUserKillsAndVictims(userId)
&& worldTimesTable.removeUserWorldTimes(userId)
&& usersTable.removeUser(uuid);
boolean success = true;
for (Table t : getAllTablesInRemoveOrder()) {
if (t instanceof UserIDTable) {
UserIDTable table = (UserIDTable) t;
success = table.removeUser(uuid);
if (!success) {
break;
}
}
}
if (success) {
return true;
}
throw new IllegalStateException("Removal Failed");
} catch (Exception e) {
Log.toLog(this.getClass().getName(), e);
rollback(); // TODO Test case
return false;
} finally {
Benchmark.stop("Database", "Remove Account");
setAvailable();
@ -272,9 +283,8 @@ public abstract class SQLDB extends Database {
*/
@Override
public boolean removeAllData() {
setStatus("Clearing all data");
try {
setStatus("Clearing all data");
for (Table table : getAllTablesInRemoveOrder()) {
if (!table.removeAllData()) {
return false;
@ -287,39 +297,14 @@ public abstract class SQLDB extends Database {
}
}
@Override
public List<UserData> getUserDataForUUIDS(Collection<UUID> uuidsCol) throws SQLException {
if (uuidsCol == null || uuidsCol.isEmpty()) {
return new ArrayList<>();
}
setStatus("Get userdata (multiple) for: " + uuidsCol.size());
Benchmark.start("Get UserData for " + uuidsCol.size());
Map<UUID, Integer> userIds = usersTable.getAllUserIds();
Set<UUID> remove = uuidsCol.stream()
.filter(uuid -> !userIds.containsKey(uuid))
.collect(Collectors.toSet());
List<UUID> uuids = new ArrayList<>(uuidsCol);
Log.debug("Database", "Data not found for: " + remove.size());
uuids.removeAll(remove);
Benchmark.start("Create UserData objects for " + userIds.size());
List<UserData> data = usersTable.getUserData(uuids);
Benchmark.stop("Database", "Create UserData objects for " + userIds.size());
if (data.isEmpty()) {
return data;
}
// TODO REWRITE
Benchmark.stop("Database", "Get UserData for " + uuidsCol.size());
setAvailable();
return data;
}
/**
* @return
*/
public boolean supportsModification() {
return supportsModification;
return new ArrayList<>();
}
private void setStatus(String status) {

View File

@ -27,7 +27,7 @@ public class SQLiteDB extends SQLDB {
* @param dbName
*/
public SQLiteDB(Plan plugin, String dbName) {
super(plugin, false);
super(plugin);
this.dbName = dbName;
}

View File

@ -19,4 +19,8 @@ public class Select extends WhereParser {
parser.append(" FROM ").append(table);
return parser;
}
public static Select all(String table) {
return new Select("SELECT * FROM " + table);
}
}

View File

@ -4,7 +4,6 @@
*/
package main.java.com.djrapitops.plan.database.tables;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.Action;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
@ -40,29 +39,22 @@ public class ActionsTable extends UserIDTable {
private final String columnActionID = "action_id";
private final String columnAdditionalInfo = "additional_info";
public ActionsTable(String name, SQLDB db, boolean usingMySQL) {
super(name, db, usingMySQL);
public ActionsTable(SQLDB db, boolean usingMySQL) {
super("plan_actions", db, usingMySQL);
}
@Override
public boolean createTable() {
ServerTable serverTable = db.getServerTable();
try {
execute(TableSqlParser.createTable(tableName)
.column(columnUserID, Sql.INT).notNull()
.column(columnServerID, Sql.INT).notNull()
.column(columnDate, Sql.LONG).notNull()
.column(columnActionID, Sql.INT).notNull()
.column(columnAdditionalInfo, Sql.varchar(100))
.foreignKey(columnUserID, usersTable.toString(), usersTable.getColumnID())
.foreignKey(columnServerID, serverTable.toString(), serverTable.getColumnID())
.toString());
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
return createTable(TableSqlParser.createTable(tableName)
.column(columnUserID, Sql.INT).notNull()
.column(columnServerID, Sql.INT).notNull()
.column(columnDate, Sql.LONG).notNull()
.column(columnActionID, Sql.INT).notNull()
.column(columnAdditionalInfo, Sql.varchar(100))
.foreignKey(columnUserID, usersTable.toString(), usersTable.getColumnID())
.foreignKey(columnServerID, serverTable.toString(), serverTable.getColumnID())
.toString());
}
public void insertAction(UUID uuid, Action action) throws SQLException {

View File

@ -1,7 +1,6 @@
package main.java.com.djrapitops.plan.database.tables;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.Select;
@ -43,21 +42,15 @@ public class CommandUseTable extends Table {
@Override
public boolean createTable() {
ServerTable serverTable = db.getServerTable();
try {
execute(TableSqlParser.createTable(tableName)
.primaryKeyIDColumn(usingMySQL, columnCommandId, Sql.INT)
.column(columnCommand, Sql.varchar(20)).notNull()
.column(columnTimesUsed, Sql.INT).notNull()
.column(columnServerID, Sql.INT).notNull()
.primaryKey(usingMySQL, columnCommandId)
.foreignKey(columnServerID, serverTable.toString(), serverTable.getColumnID())
.toString()
);
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
return createTable(TableSqlParser.createTable(tableName)
.primaryKeyIDColumn(usingMySQL, columnCommandId, Sql.INT)
.column(columnCommand, Sql.varchar(20)).notNull()
.column(columnTimesUsed, Sql.INT).notNull()
.column(columnServerID, Sql.INT).notNull()
.primaryKey(usingMySQL, columnCommandId)
.foreignKey(columnServerID, serverTable.toString(), serverTable.getColumnID())
.toString()
);
}
/**

View File

@ -1,6 +1,5 @@
package main.java.com.djrapitops.plan.database.tables;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.Select;
import main.java.com.djrapitops.plan.database.sql.Sql;
@ -37,28 +36,13 @@ public class IPsTable extends UserIDTable {
*/
@Override
public boolean createTable() {
UsersTable usersTable = db.getUsersTable();
try {
execute(TableSqlParser.createTable(tableName)
.column(columnUserID, Sql.INT).notNull()
.column(columnIP, Sql.varchar(20)).notNull()
.column(columnGeolocation, Sql.varchar(50)).notNull()
.foreignKey(columnUserID, usersTable.getTableName(), usersTable.getColumnID())
.toString()
);
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
}
/**
* @param userId The User ID from which the IPs should be removed from
* @return if the IPs were removed successfully
*/
public boolean removeUserIPs(int userId) {
return super.removeDataOf(userId);
return createTable(TableSqlParser.createTable(tableName)
.column(columnUserID, Sql.INT).notNull()
.column(columnIP, Sql.varchar(20)).notNull()
.column(columnGeolocation, Sql.varchar(50)).notNull()
.foreignKey(columnUserID, usersTable.getTableName(), usersTable.getColumnID())
.toString()
);
}
/**

View File

@ -3,27 +3,30 @@ package main.java.com.djrapitops.plan.database.tables;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.KillData;
import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.Sql;
import main.java.com.djrapitops.plan.database.sql.TableSqlParser;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* @author Rsl1122
*/
public class KillsTable extends Table {
public class KillsTable extends UserIDTable {
private final String columnKillerUserID = "killer_id";
private final String columnVictimUserID = "victim_id";
private final String columnWeapon = "weapon";
private final String columnDate = "date";
private final String columnServerID = "server_id"; //TODO
private final String columnSessionID = "session_id"; //TODO
private final String columnSessionID = "session_id";
private final SessionsTable sessionsTable;
/**
* @param db
@ -31,6 +34,7 @@ public class KillsTable extends Table {
*/
public KillsTable(SQLDB db, boolean usingMySQL) {
super("plan_kills", db, usingMySQL);
sessionsTable = db.getSessionsTable();
}
/**
@ -38,194 +42,110 @@ public class KillsTable extends Table {
*/
@Override
public boolean createTable() {
UsersTable usersTable = db.getUsersTable();
try {
execute(TableSqlParser.createTable(tableName)
.column(columnKillerUserID, Sql.INT).notNull()
.column(columnVictimUserID, Sql.INT).notNull()
.column(columnWeapon, Sql.varchar(30)).notNull()
.column(columnDate, Sql.LONG).notNull()
.foreignKey(columnKillerUserID, usersTable.getTableName(), usersTable.getColumnID())
.foreignKey(columnVictimUserID, usersTable.getTableName(), usersTable.getColumnID())
.toString()
);
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
return createTable(TableSqlParser.createTable(tableName)
.column(columnKillerUserID, Sql.INT).notNull()
.column(columnVictimUserID, Sql.INT).notNull()
.column(columnWeapon, Sql.varchar(30)).notNull()
.column(columnDate, Sql.LONG).notNull()
.column(columnSessionID, Sql.LONG).notNull()
.foreignKey(columnKillerUserID, usersTable.getTableName(), usersTable.getColumnID())
.foreignKey(columnVictimUserID, usersTable.getTableName(), usersTable.getColumnID())
.foreignKey(columnSessionID, sessionsTable.getTableName(), sessionsTable.getColumnID())
.toString()
);
}
/**
* @param userId
* @return
*/
public boolean removeUserKillsAndVictims(int userId) {
@Override
public boolean removeUser(UUID uuid) {
PreparedStatement statement = null;
try {
statement = prepareStatement("DELETE FROM " + tableName + " WHERE " + columnKillerUserID + " = ? OR " + columnVictimUserID + " = ?");
statement.setInt(1, userId);
statement.setInt(2, userId);
statement = prepareStatement("DELETE FROM " + tableName +
" WHERE " + columnKillerUserID + " = " + usersTable.statementSelectID +
" OR " + columnVictimUserID + " = " + usersTable.statementSelectID);
statement.setString(1, uuid.toString());
statement.setString(2, uuid.toString());
statement.execute();
commit(statement.getConnection());
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
} finally {
try {
endTransaction(statement);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
close(statement);
}
}
/**
* @param userId
* @return
* @throws SQLException
*/
public List<KillData> getPlayerKills(int userId) throws SQLException {
UsersTable usersTable = db.getUsersTable();
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT * FROM " + tableName + " WHERE (" + columnKillerUserID + "=?)");
statement.setInt(1, userId);
set = statement.executeQuery();
List<KillData> killData = new ArrayList<>();
while (set.next()) {
UUID victimUUID = null; // TODO Victim UUID Retrieval
killData.add(new KillData(victimUUID, set.getString(columnWeapon), set.getLong(columnDate)));
}
return killData;
} finally {
endTransaction(statement);
close(set, statement);
}
}
/**
* @param userId
* @param kills
* @throws SQLException
*/
public void savePlayerKills(int userId, List<KillData> kills) throws SQLException {
if (Verify.isEmpty(kills)) {
public void savePlayerKills(UUID uuid, long sessionID, List<KillData> playerKills) throws SQLException {
if (Verify.isEmpty(playerKills)) {
return;
}
Benchmark.start("Save Kills");
kills.removeAll(getPlayerKills(userId));
PreparedStatement statement = null;
try {
statement = prepareStatement("INSERT INTO " + tableName + " ("
+ columnKillerUserID + ", "
+ columnVictimUserID + ", "
+ columnWeapon + ", "
+ columnDate
+ ") VALUES (?, ?, ?, ?)");
for (KillData kill : kills) {
if (kill == null) {
continue;
}
statement.setInt(1, userId);
statement.setInt(2, -1); // TODO Victim ID Retrieval
statement.setString(3, kill.getWeapon());
statement.setLong(4, kill.getTime());
+ columnSessionID + ", "
+ columnDate + ", "
+ columnWeapon
+ ") VALUES ("
+ usersTable.statementSelectID + ", "
+ usersTable.statementSelectID + ", "
+ "?, ?, ?)");
for (KillData kill : playerKills) {
UUID victim = kill.getVictim();
long date = kill.getTime();
String weapon = kill.getWeapon();
statement.setString(1, uuid.toString());
statement.setString(2, victim.toString());
statement.setLong(3, sessionID);
statement.setLong(4, date);
statement.setString(5, weapon);
statement.addBatch();
}
statement.executeBatch();
} finally {
endTransaction(statement);
close(statement);
Benchmark.stop("Database", "Save Kills");
}
}
/**
* @param ids
* @param uuids
* @return
* @throws SQLException
*/
public Map<Integer, List<KillData>> getPlayerKills(Collection<Integer> ids, Map<Integer, UUID> uuids) throws SQLException {
if (ids == null || ids.isEmpty()) {
return new HashMap<>();
}
Benchmark.start("Get Kills multiple");
public void addKillsToSessions(UUID uuid, Map<Long, Session> sessions) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
Map<Integer, List<KillData>> kills = new HashMap<>();
statement = prepareStatement("SELECT * FROM " + tableName);
String usersIDColumn = usersTable + "." + usersTable.getColumnID();
String usersUUIDColumn = usersTable + "." + usersTable.getColumnUUID() + " as victim_uuid";
statement = prepareStatement("SELECT " +
columnSessionID + ", " +
columnDate + ", " +
columnWeapon + ", " +
usersUUIDColumn +
" FROM " + tableName +
" WHERE " + columnKillerUserID + "=" + usersTable.statementSelectID +
" JOIN " + usersTable + " on " + usersIDColumn + "=" + columnVictimUserID); // Might not work TODO TEST
statement.setString(1, uuid.toString());
set = statement.executeQuery();
for (Integer id : ids) {
kills.put(id, new ArrayList<>());
}
while (set.next()) {
int killerID = set.getInt(columnKillerUserID);
if (!ids.contains(killerID)) {
long sessionID = set.getLong(columnSessionID);
Session session = sessions.get(sessionID);
if (session == null) {
continue;
}
UUID victimUUID = null; // TODO Victim UUID Retrieval
kills.get(killerID).add(new KillData(victimUUID, set.getString(columnWeapon), set.getLong(columnDate)));
String uuidS = set.getString("victim_uuid");
UUID victim = UUID.fromString(uuidS);
long date = set.getLong(columnDate);
String weapon = set.getString(columnWeapon);
session.getPlayerKills().add(new KillData(victim, weapon, date));
}
return kills;
} finally {
endTransaction(statement);
close(set, statement);
Benchmark.stop("Database", "Get Kills multiple");
}
}
/**
* @param kills
* @param uuids
* @throws SQLException
*/
public void savePlayerKills(Map<Integer, List<KillData>> kills, Map<Integer, UUID> uuids) throws SQLException {
if (Verify.isEmpty(kills)) {
return;
}
Benchmark.start("Save Kills multiple");
Map<Integer, List<KillData>> saved = getPlayerKills(kills.keySet(), uuids);
PreparedStatement statement = null;
try {
statement = prepareStatement("INSERT INTO " + tableName + " ("
+ columnKillerUserID + ", "
+ columnVictimUserID + ", "
+ columnWeapon + ", "
+ columnDate
+ ") VALUES (?, ?, ?, ?)");
for (Map.Entry<Integer, List<KillData>> entrySet : kills.entrySet()) {
Integer id = entrySet.getKey();
List<KillData> playerKills = entrySet.getValue();
playerKills.removeIf(Objects::isNull);
List<KillData> s = saved.get(id);
if (s != null) {
playerKills.removeAll(s);
}
for (KillData kill : playerKills) {
statement.setInt(1, id);
statement.setInt(2, -1); // TODO Victim ID Retrieval
statement.setString(3, kill.getWeapon());
statement.setLong(4, kill.getTime());
statement.addBatch();
}
statement.executeBatch();
}
} finally {
endTransaction(statement);
close(statement);
Benchmark.stop("Database", "Save Kills multiple");
}
}
public void savePlayerKills(UUID uuid, List<KillData> playerKills) {
// TODO savePlayerKills
}
// TODO getPlayerKills (UUID)
}

View File

@ -1,16 +1,16 @@
package main.java.com.djrapitops.plan.database.tables;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.Sql;
import main.java.com.djrapitops.plan.database.sql.TableSqlParser;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @author Rsl1122
@ -18,8 +18,9 @@ import java.util.*;
public class NicknamesTable extends UserIDTable {
private final String columnNick = "nickname";
private final String columnCurrent = "current_nick";
private final String columnServerID = "server_id"; //TODO
private final String columnServerID = "server_id";
private ServerTable serverTable;
/**
* @param db The database
@ -27,6 +28,7 @@ public class NicknamesTable extends UserIDTable {
*/
public NicknamesTable(SQLDB db, boolean usingMySQL) {
super("plan_nicknames", db, usingMySQL);
serverTable = db.getServerTable();
}
/**
@ -34,69 +36,44 @@ public class NicknamesTable extends UserIDTable {
*/
@Override
public boolean createTable() {
UsersTable usersTable = db.getUsersTable();
try {
execute(TableSqlParser.createTable(tableName)
.column(columnUserID, Sql.INT).notNull()
.column(columnNick, Sql.varchar(75)).notNull()
.column(columnCurrent, Sql.BOOL).notNull().defaultValue(false)
.foreignKey(columnUserID, usersTable.getTableName(), usersTable.getColumnID())
.toString()
);
if (getVersion() < 3) {
alterTablesV3();
}
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
}
private void alterTablesV3() {
addColumns(columnCurrent + " boolean NOT NULL DEFAULT 0");
return createTable(TableSqlParser.createTable(tableName)
.column(columnUserID, Sql.INT).notNull()
.column(columnNick, Sql.varchar(75)).notNull()
.column(columnServerID, Sql.INT).notNull()
.foreignKey(columnUserID, usersTable.getTableName(), usersTable.getColumnID())
.foreignKey(columnServerID, serverTable.getTableName(), serverTable.getColumnID())
.toString()
);
}
/**
* @param userId The User ID from which the nicknames should be removed from
* @return if the removal was successful
*/
public boolean removeUserNicknames(int userId) {
return super.removeDataOf(userId);
}
/**
* @param userId The User ID from which the nicknames should be retrieved from
* Get ALL nicknames of the user.
* <p>
* Get's nicknames from other servers as well.
*
* @param uuid UUID of the Player
* @return The nicknames of the User
* @throws SQLException when an error at retrieval happens
*/
public List<String> getNicknames(int userId) throws SQLException {
public List<String> getAllNicknames(UUID uuid) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT * FROM " + tableName + " WHERE (" + columnUserID + "=?)");
statement.setInt(1, userId);
statement = prepareStatement("SELECT " + columnNick + " FROM " + tableName +
" WHERE (" + columnUserID + "=" + usersTable.statementSelectID + ")");
statement.setString(1, uuid.toString());
set = statement.executeQuery();
List<String> nicknames = new ArrayList<>();
String lastNick = "";
while (set.next()) {
String nickname = set.getString(columnNick);
if (nickname.isEmpty()) {
continue;
}
nicknames.add(nickname);
if (set.getBoolean(columnCurrent)) {
lastNick = nickname;
if (!nicknames.contains(nickname)) {
nicknames.add(nickname);
}
}
if (!lastNick.isEmpty()) {
nicknames.set(nicknames.size() - 1, lastNick);
}
return nicknames;
} finally {
endTransaction(statement);
@ -105,150 +82,80 @@ public class NicknamesTable extends UserIDTable {
}
/**
* @param userId The User ID for which the nicknames should be saved for
* @param names The nicknames
* @param lastNick The latest nickname
* @throws SQLException when an error at saving happens
* Get nicknames of the user on THIS server.
* <p>
* Get's nicknames from other servers as well.
*
* @param uuid UUID of the Player
* @return The nicknames of the User
* @throws SQLException when an error at retrieval happens
*/
public void saveNickList(int userId, Set<String> names, String lastNick) throws SQLException {
if (Verify.isEmpty(names)) {
return;
}
names.removeAll(getNicknames(userId));
if (names.isEmpty()) {
return;
}
PreparedStatement statement = null;
try {
statement = prepareStatement("INSERT INTO " + tableName + " ("
+ columnUserID + ", "
+ columnCurrent + ", "
+ columnNick
+ ") VALUES (?, ?, ?)");
for (String name : names) {
statement.setInt(1, userId);
statement.setInt(2, name.equals(lastNick) ? 1 : 0);
statement.setString(3, name);
statement.addBatch();
}
statement.executeBatch();
} finally {
endTransaction(statement);
close(statement);
}
public List<String> getNicknames(UUID uuid) throws SQLException {
return getNicknames(uuid, Plan.getServerUUID());
}
/**
* @param ids The User IDs for which the nicknames should be retrieved for
* @return The User ID corresponding with the nicknames
* Get nicknames of the user on a server.
* <p>
* Get's nicknames from other servers as well.
*
* @param uuid UUID of the Player
* @param serverUUID UUID of the server
* @return The nicknames of the User
* @throws SQLException when an error at retrieval happens
*/
public Map<Integer, List<String>> getNicknames(Collection<Integer> ids) throws SQLException {
if (Verify.isEmpty(ids)) {
return new HashMap<>();
}
Benchmark.start("Get Nicknames Multiple");
public List<String> getNicknames(UUID uuid, UUID serverUUID) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
Map<Integer, List<String>> nicks = new HashMap<>();
Map<Integer, String> lastNicks = new HashMap<>();
for (Integer id : ids) {
nicks.put(id, new ArrayList<>());
}
statement = prepareStatement("SELECT * FROM " + tableName);
statement = prepareStatement("SELECT " + columnNick + " FROM " + tableName +
" WHERE (" + columnUserID + "=" + usersTable.statementSelectID + ")" +
" AND " + columnServerID + "=" + serverTable.statementSelectServerID
);
statement.setString(1, uuid.toString());
statement.setString(2, serverUUID.toString());
set = statement.executeQuery();
while (set.next()) {
Integer id = set.getInt(columnUserID);
String nickname = set.getString(columnNick);
if (!ids.contains(id) || nickname.isEmpty()) {
List<String> nicknames = new ArrayList<>();
while (set.next()) {
String nickname = set.getString(columnNick);
if (nickname.isEmpty()) {
continue;
}
nicks.get(id).add(nickname);
if (set.getBoolean(columnCurrent)) {
lastNicks.put(id, nickname);
if (!nicknames.contains(nickname)) {
nicknames.add(nickname);
}
}
for (Map.Entry<Integer, String> entry : lastNicks.entrySet()) {
Integer id = entry.getKey();
String lastNick = entry.getValue();
List<String> list = nicks.get(id);
// Moves the last known nickname to the end of the List.
// This is due to the way nicknames are added to UserData,
// Nicknames are stored as a Set and last Nickname is a separate String.
list.set(list.size() - 1, lastNick);
}
return nicks;
return nicknames;
} finally {
endTransaction(statement);
close(set, statement);
Benchmark.stop("Database", "Get Nicknames Multiple");
}
}
/**
* @param nicknames The User ID corresponding to the nicknames
* @param lastNicks The User ID corresponding with the last nick they inherited
* @throws SQLException when an error at saving happens
*/
public void saveNickLists(Map<Integer, Set<String>> nicknames, Map<Integer, String> lastNicks) throws SQLException {
if (Verify.isEmpty(nicknames)) {
public void saveUserName(UUID uuid, String displayName) throws SQLException {
List<String> saved = getNicknames(uuid);
if (saved.contains(displayName)) {
return;
}
Benchmark.start("Save Nicknames Multiple");
Map<Integer, List<String>> saved = getNicknames(nicknames.keySet());
PreparedStatement statement = null;
try {
statement = prepareStatement("INSERT INTO " + tableName + " ("
+ columnUserID + ", "
+ columnCurrent + ", "
+ columnNick
+ ") VALUES (?, ?, ?)");
for (Map.Entry<Integer, Set<String>> entrySet : nicknames.entrySet()) {
Integer id = entrySet.getKey();
Set<String> newNicks = entrySet.getValue();
String lastNick = lastNicks.get(id);
List<String> s = saved.get(id);
if (s != null) {
newNicks.removeAll(s);
}
if (newNicks.isEmpty()) {
continue;
}
for (String name : newNicks) {
statement.setInt(1, id);
statement.setInt(2, (name.equals(lastNick)) ? 1 : 0);
statement.setString(3, name);
statement.addBatch();
}
}
statement.executeBatch();
statement = prepareStatement("INSERT INTO " + tableName + " (" +
columnUserID + ", " +
columnServerID + ", " +
columnNick +
") VALUES (" +
usersTable.statementSelectID + ", " +
serverTable.statementSelectServerID + ", " +
"?)");
statement.setString(1, uuid.toString());
statement.setString(2, Plan.getServerUUID().toString());
statement.setString(3, displayName);
statement.execute();
} finally {
endTransaction(statement);
close(statement);
Benchmark.stop("Database", "Save Nicknames Multiple");
}
}
}

View File

@ -8,6 +8,8 @@ package main.java.com.djrapitops.plan.database.tables;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.Insert;
import main.java.com.djrapitops.plan.database.sql.Select;
import main.java.com.djrapitops.plan.database.sql.Sql;
import main.java.com.djrapitops.plan.database.sql.TableSqlParser;
@ -22,31 +24,22 @@ import java.util.List;
*/
public class SecurityTable extends Table {
private final String columnUser;
private final String columnSaltedHash;
private final String columnPermLevel;
private final String columnUser = "username";
private final String columnSaltedHash = "salted_pass_hash";
private final String columnPermLevel = "permission_level";
public SecurityTable(SQLDB db, boolean usingMySQL) {
super("plan_security", db, usingMySQL);
columnUser = "username";
columnSaltedHash = "salted_pass_hash";
columnPermLevel = "permission_level";
}
@Override
public boolean createTable() {
try {
execute(TableSqlParser.createTable(tableName)
.column(columnUser, Sql.varchar(100)).notNull().unique()
.column(columnSaltedHash, Sql.varchar(100)).notNull().unique()
.column(columnPermLevel, Sql.INT).notNull()
.toString()
);
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
return createTable(TableSqlParser.createTable(tableName)
.column(columnUser, Sql.varchar(100)).notNull().unique()
.column(columnSaltedHash, Sql.varchar(100)).notNull().unique()
.column(columnPermLevel, Sql.INT).notNull()
.toString()
);
}
public boolean removeUser(String user) {
@ -77,11 +70,10 @@ public class SecurityTable extends Table {
public void addNewUser(String user, String saltPassHash, int permLevel) throws SQLException {
PreparedStatement statement = null;
try {
statement = prepareStatement("INSERT INTO " + tableName + " ("
+ columnUser + ", "
+ columnSaltedHash + ", "
+ columnPermLevel
+ ") VALUES (?, ?, ?)");
statement = prepareStatement(Insert.values(tableName,
columnUser,
columnSaltedHash,
columnPermLevel));
statement.setString(1, user);
statement.setString(2, saltPassHash);
statement.setInt(3, permLevel);
@ -101,7 +93,7 @@ public class SecurityTable extends Table {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT * FROM " + tableName + " WHERE (" + columnUser + "=?)");
statement = prepareStatement(Select.all(tableName).where(columnUser + "=?").toString());
statement.setString(1, user);
set = statement.executeQuery();
if (set.next()) {
@ -120,7 +112,7 @@ public class SecurityTable extends Table {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT * FROM " + tableName);
statement = prepareStatement(Select.all(tableName).toString());
set = statement.executeQuery();
List<WebUser> list = new ArrayList<>();
while (set.next()) {

View File

@ -5,7 +5,6 @@
package main.java.com.djrapitops.plan.database.tables;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.server.ServerInfo;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.*;
@ -49,20 +48,15 @@ public class ServerTable extends Table {
@Override
public boolean createTable() {
try {
execute(TableSqlParser.createTable(tableName)
.primaryKeyIDColumn(usingMySQL, columnServerID, Sql.INT)
.column(columnServerUUID, Sql.varchar(36)).notNull().unique()
.column(columnServerName, Sql.varchar(100))
.column(columnWebserverAddress, Sql.varchar(100))
.column(columnInstalled, Sql.BOOL).notNull().defaultValue(false)
.primaryKey(usingMySQL, columnServerID)
.toString());
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
return createTable(TableSqlParser.createTable(tableName)
.primaryKeyIDColumn(usingMySQL, columnServerID, Sql.INT)
.column(columnServerUUID, Sql.varchar(36)).notNull().unique()
.column(columnServerName, Sql.varchar(100))
.column(columnWebserverAddress, Sql.varchar(100))
.column(columnInstalled, Sql.BOOL).notNull().defaultValue(false)
.primaryKey(usingMySQL, columnServerID)
.toString()
);
}
public void saveCurrentServerInfo(ServerInfo info) throws SQLException {

View File

@ -1,6 +1,5 @@
package main.java.com.djrapitops.plan.database.tables;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
@ -12,13 +11,17 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author Rsl1122
*/
public class SessionsTable extends UserIDTable {
private final String columnSessionID = "id";
// TODO getLastPlayed(UUID, UUID)
private final String columnID = "id";
private final String columnSessionStart = "session_start";
private final String columnSessionEnd = "session_end";
private final String columnServerID = "server_id";
@ -41,42 +44,50 @@ public class SessionsTable extends UserIDTable {
*/
@Override
public boolean createTable() {
try {
String serverTableName = serverTable.getTableName();
String serverTableID = serverTable.getColumnID();
String sql = TableSqlParser.createTable(this.tableName)
.primaryKeyIDColumn(usingMySQL, columnSessionID, Sql.LONG)
.column(columnUserID, Sql.INT).notNull()
.column(columnServerID, Sql.INT).notNull()
.column(columnSessionStart, Sql.LONG).notNull()
.column(columnSessionEnd, Sql.LONG).notNull()
.column(columnMobKills, Sql.INT).notNull()
.column(columnDeaths, Sql.INT).notNull()
.foreignKey(columnUserID, usersTable.getTableName(), usersTable.getColumnID())
.foreignKey(columnServerID, serverTableName, serverTableID)
.primaryKey(usingMySQL, columnSessionID)
.toString();
execute(sql);
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
return createTable(TableSqlParser.createTable(this.tableName)
.primaryKeyIDColumn(usingMySQL, columnID, Sql.LONG)
.column(columnUserID, Sql.INT).notNull()
.column(columnServerID, Sql.INT).notNull()
.column(columnSessionStart, Sql.LONG).notNull()
.column(columnSessionEnd, Sql.LONG).notNull()
.column(columnMobKills, Sql.INT).notNull()
.column(columnDeaths, Sql.INT).notNull()
.foreignKey(columnUserID, usersTable.getTableName(), usersTable.getColumnID())
.foreignKey(columnServerID, serverTable.getTableName(), serverTable.getColumnID())
.primaryKey(usingMySQL, columnID)
.toString()
);
}
/**
* Removes User's Sessions from the Database.
* Used to save a session, with all it's information into the database.
* <p>
* // TODO KILLS SHOULD BE REMOVED FIRST.
* Also saves WorldTimes and Kills.
*
* @param userId
* @return
* @param uuid UUID of the player.
* @param session Session of the player that has ended ({@code endSession} has been called)
* @throws SQLException
*/
public boolean removeUserSessions(int userId) {
return super.removeDataOf(userId);
public void saveSession(UUID uuid, Session session) throws SQLException {
saveSessionInformation(uuid, session);
long sessionID = getSessionID(uuid, session);
if (sessionID == -1) {
throw new IllegalStateException("Session was not Saved!");
}
db.getWorldTimesTable().saveWorldTimes(uuid, sessionID, session.getWorldTimes());
db.getKillsTable().savePlayerKills(uuid, sessionID, session.getPlayerKills());
}
public void saveSessionInformation(UUID uuid, Session session) throws SQLException {
/**
* Saves Session's Information to the Session Table.
* <p>
* Does not save Kills or WorldTimes.
*
* @param uuid UUID of the player.
* @param session Session of the player that has ended ({@code endSession} has been called)
* @throws SQLException
*/
private void saveSessionInformation(UUID uuid, Session session) throws SQLException {
PreparedStatement statement = null;
try {
statement = prepareStatement("INSERT INTO " + tableName + " ("
@ -87,7 +98,7 @@ public class SessionsTable extends UserIDTable {
+ columnMobKills + ", "
+ columnServerID
+ ") VALUES ("
+ columnUserID + "=" + usersTable.statementSelectID + ", "
+ usersTable.statementSelectID + ", "
+ "?, ?, ?, ?, "
+ serverTable.statementSelectServerID + ")");
statement.setString(1, uuid.toString());
@ -103,12 +114,48 @@ public class SessionsTable extends UserIDTable {
endTransaction(statement);
close(statement);
}
db.getWorldTimesTable().saveWorldTimes(session.getWorldTimes());
db.getKillsTable().savePlayerKills(uuid, session.getPlayerKills());
}
public Map<String, List<Session>> getSessions(UUID uuid) throws SQLException {
/**
* Used to get the sessionID of a newly inserted row.
*
* @param uuid UUID of the player
* @param session session inserted.
* @return ID of the inserted session or -1 if session has not been inserted.
*/
private long getSessionID(UUID uuid, Session session) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT " + columnID + " FROM " + tableName +
" WHERE " + columnUserID + "=" + usersTable.statementSelectID +
" AND " + columnSessionStart + "=?" +
" AND " + columnSessionEnd + "=?");
statement.setString(1, uuid.toString());
statement.setLong(2, session.getSessionStart());
statement.setLong(3, session.getSessionEnd());
set = statement.executeQuery();
if (set.next()) {
return set.getLong(columnID);
}
return -1L;
} finally {
endTransaction(statement);
close(set, statement);
}
}
/**
* Returns a Map containing Lists of sessions, key as ServerName.
* <p>
* Does not include Kills or WorldTimes.
* Use {@code getSessions} to get full Sessions.
*
* @param uuid UUID of the player
* @return Map with Sessions that don't contain Kills or WorldTimes.
* @throws SQLException
*/
private Map<String, List<Session>> getSessionInformation(UUID uuid) throws SQLException {
Map<Integer, String> serverNames = serverTable.getServerNames();
Map<String, List<Session>> sessionsByServer = new HashMap<>();
PreparedStatement statement = null;
@ -120,7 +167,7 @@ public class SessionsTable extends UserIDTable {
statement.setString(1, uuid.toString());
set = statement.executeQuery();
while (set.next()) {
long id = set.getLong(columnSessionID);
long id = set.getLong(columnID);
long start = set.getLong(columnSessionStart);
long end = set.getLong(columnSessionEnd);
String serverName = serverNames.get(set.getInt(columnServerID));
@ -137,23 +184,57 @@ public class SessionsTable extends UserIDTable {
}
}
public Map<String, List<Session>> getSessions(UUID uuid) throws SQLException {
Map<String, List<Session>> sessions = getSessionInformation(uuid);
Map<Long, Session> allSessions = sessions.values().stream().flatMap(Collection::stream).collect(Collectors.toMap(Session::getSessionID, Function.identity()));
db.getKillsTable().addKillsToSessions(uuid, allSessions);
db.getWorldTimesTable().addWorldTimesToSessions(uuid, allSessions);
return sessions;
}
/**
* Get Total Playtime of a Player on THIS server.
*
* @param uuid UUID of the player.
* @return Milliseconds played on THIS server. 0 if player or server not found.
* @throws SQLException
*/
public long getPlaytime(UUID uuid) throws SQLException {
return getPlaytime(uuid, Plan.getServerUUID());
}
/**
* Get Total Playtime of a Player on a server.
*
* @param uuid UUID of the player.
* @param serverUUID UUID of the server. @see ServerTable
* @return Milliseconds played on the server. 0 if player or server not found.
* @throws SQLException
*/
public long getPlaytime(UUID uuid, UUID serverUUID) throws SQLException {
return getPlaytime(uuid, serverUUID, 0L);
}
/**
* Used to get Playtime after Epoch ms on a server.
*
* @param uuid UUID of the player.
* @param serverUUID UUID of the server. @see ServerTable
* @param afterDate Epoch ms (Playtime after this date is calculated)
* @return Milliseconds played after given epoch ms on the server. 0 if player or server not found.
* @throws SQLException
*/
public long getPlaytime(UUID uuid, UUID serverUUID, long afterDate) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT FROM " + tableName + " "
+ "(SUM(" + columnSessionEnd + ") - SUM(" + columnSessionStart + ")) as playtime "
+ "WHERE " + columnSessionStart + ">? AND "
+ columnUserID + "=" + usersTable.statementSelectID + " AND "
+ columnServerID + "=" + serverTable.statementSelectServerID);
statement = prepareStatement("SELECT" +
" (SUM(" + columnSessionEnd + ") - SUM(" + columnSessionStart + ")) as playtime" +
" FROM " + tableName +
" WHERE " + columnSessionStart + ">?" +
" AND " + columnUserID + "=" + usersTable.statementSelectID +
" AND " + columnServerID + "=" + serverTable.statementSelectServerID);
statement.setLong(1, afterDate);
statement.setString(2, uuid.toString());
statement.setString(3, serverUUID.toString());
@ -163,23 +244,167 @@ public class SessionsTable extends UserIDTable {
}
return 0;
} finally {
endTransaction(statement);
close(set, statement);
}
}
/**
* Used to get Totals of Playtime in a Map, sorted by ServerNames.
*
* @param uuid UUID of the Player.
* @return key - ServerName, value ms played
* @throws SQLException
*/
public Map<String, Long> getPlaytimeByServer(UUID uuid) throws SQLException {
return getPlaytimeByServer(uuid, 0L);
}
/**
* Used to get Playtimes after a date in a Map, sorted by ServerNames.
*
* @param uuid UUID of the Player.
* @param afterDate Epoch ms (Playtime after this date is calculated)
* @return key - ServerName, value ms played
* @throws SQLException
*/
public Map<String, Long> getPlaytimeByServer(UUID uuid, long afterDate) throws SQLException {
Map<Integer, String> serverNames = serverTable.getServerNames();
Map<String, Long> playtimes = new HashMap<>();
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT FROM " + tableName + " "
+ "(SUM(" + columnSessionEnd + ") - SUM(" + columnSessionStart + ")) as playtime "
+ "WHERE " + columnSessionStart + ">? AND "
+ columnUserID + "=" + usersTable.statementSelectID); // TODO CONTINUE
statement = prepareStatement("SELECT " +
"(SUM(" + columnSessionEnd + ") - SUM(" + columnSessionStart + ")) as playtime, " +
columnServerID + "," +
" FROM " + tableName +
" WHERE " + columnSessionStart + ">?" +
" AND " + columnUserID + "=" + usersTable.statementSelectID);
statement.setLong(1, afterDate);
statement.setString(2, uuid.toString());
set = statement.executeQuery();
while (set.next()) {
String serverName = serverNames.get(set.getInt(columnServerID));
long playtime = set.getLong("playtime");
playtimes.put(serverName, playtime);
}
return playtimes;
} finally {
endTransaction(statement);
close(set, statement);
}
}
/**
* Used to get the Total Playtime of a Server.
*
* @param serverUUID UUID of the server.
* @return Milliseconds played on the server. 0 if server not found.
* @throws SQLException
*/
public long getPlaytimeOfServer(UUID serverUUID) throws SQLException {
return getPlaytimeOfServer(serverUUID, 0L);
}
/**
* Used to get Playtime after a date of a Server.
*
* @param serverUUID UUID of the server.
* @param afterDate Epoch ms (Playtime after this date is calculated)
* @return Milliseconds played after given epoch ms on the server. 0 if server not found.
* @throws SQLException
*/
public long getPlaytimeOfServer(UUID serverUUID, long afterDate) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT" +
" (SUM(" + columnSessionEnd + ") - SUM(" + columnSessionStart + ")) as playtime" +
" FROM " + tableName +
" WHERE " + columnSessionStart + ">?" +
" AND " + columnServerID + "=" + serverTable.statementSelectServerID);
statement.setLong(1, afterDate);
statement.setString(2, serverUUID.toString());
set = statement.executeQuery();
if (set.next()) {
return set.getLong("playtime");
}
return 0;
} finally {
endTransaction(statement);
close(set, statement);
}
}
/**
* Used to get total Session count of a Player on THIS server.
*
* @param uuid UUID of the player.
* @return How many sessions player has. 0 if player or server not found.
* @throws SQLException
*/
public int getSessionCount(UUID uuid) throws SQLException {
return getSessionCount(uuid, 0L);
}
/**
* Used to get total Session count of a Player on THIS server after a given epoch ms.
*
* @param uuid UUID of the player.
* @param afterDate Epoch ms (Session count after this date is calculated)
* @return How many sessions player has. 0 if player or server not found.
* @throws SQLException
*/
public int getSessionCount(UUID uuid, long afterDate) throws SQLException {
return getSessionCount(uuid, Plan.getServerUUID(), afterDate);
}
/**
* Used to get total Session count of a Player on a server.
*
* @param uuid UUID of the player.
* @param serverUUID UUID of the server.
* @return How many sessions player has. 0 if player or server not found.
* @throws SQLException
*/
public int getSessionCount(UUID uuid, UUID serverUUID) throws SQLException {
return getSessionCount(uuid, serverUUID, 0L);
}
/**
* Used to get total Session count of a Player on a server after a given epoch ms.
*
* @param uuid UUID of the player.
* @param serverUUID UUID of the server.
* @param afterDate Epoch ms (Session count after this date is calculated)
* @return How many sessions player has. 0 if player or server not found.
* @throws SQLException
*/
public int getSessionCount(UUID uuid, UUID serverUUID, long afterDate) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT" +
" (COUNT(" + columnID + ") - SUM(" + columnSessionStart + ")) as logintimes" +
" FROM " + tableName +
" WHERE " + columnSessionStart + ">?" +
" AND " + columnUserID + "=" + usersTable.statementSelectID +
" AND " + columnServerID + "=" + serverTable.statementSelectServerID);
statement.setLong(1, afterDate);
statement.setString(2, uuid.toString());
statement.setString(3, serverUUID.toString());
set = statement.executeQuery();
if (set.next()) {
return set.getInt("logintimes");
}
return 0;
} finally {
endTransaction(statement);
close(set, statement);
}
}
public String getColumnID() {
return columnID;
}
}

View File

@ -5,6 +5,7 @@ import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.database.DBUtils;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.Select;
import main.java.com.djrapitops.plan.database.sql.Sql;
import main.java.com.djrapitops.plan.database.sql.TableSqlParser;
import main.java.com.djrapitops.plan.utilities.Benchmark;
@ -24,14 +25,14 @@ import java.util.List;
*/
public class TPSTable extends Table {
private final String columnServerID; //TODO
private final String columnDate;
private final String columnTPS;
private final String columnPlayers;
private final String columnCPUUsage;
private final String columnRAMUsage;
private final String columnEntities;
private final String columnChunksLoaded;
private final String columnServerID = "server_id"; //TODO
private final String columnDate = "date";
private final String columnTPS = "tps";
private final String columnPlayers = "players_online";
private final String columnCPUUsage = "cpu_usage";
private final String columnRAMUsage = "ram_usage";
private final String columnEntities = "entities";
private final String columnChunksLoaded = "chunks_loaded";
/**
* @param db
@ -39,52 +40,19 @@ public class TPSTable extends Table {
*/
public TPSTable(SQLDB db, boolean usingMySQL) {
super("plan_tps", db, usingMySQL);
columnServerID = "server_id";
columnDate = "date";
columnTPS = "tps";
columnPlayers = "players_online";
columnCPUUsage = "cpu_usage";
columnRAMUsage = "ram_usage";
columnEntities = "entities";
columnChunksLoaded = "chunks_loaded";
}
@Override
public boolean createTable() {
try {
execute(TableSqlParser.createTable(tableName)
.column(columnDate, Sql.LONG).notNull()
.column(columnTPS, Sql.DOUBLE).notNull()
.column(columnPlayers, Sql.INT).notNull()
.column(columnCPUUsage, Sql.DOUBLE).notNull()
.column(columnRAMUsage, Sql.LONG).notNull()
.column(columnEntities, Sql.INT).notNull()
.column(columnChunksLoaded, Sql.INT).notNull()
.toString()
);
int version = getVersion();
if (version < 6) {
alterTablesV6();
}
if (version < 7) {
alterTablesV7();
}
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
}
private void alterTablesV6() {
addColumns(columnCPUUsage + " double NOT NULL DEFAULT 0");
}
private void alterTablesV7() {
addColumns(
columnRAMUsage + " bigint NOT NULL DEFAULT 0",
columnEntities + " integer NOT NULL DEFAULT 0",
columnChunksLoaded + " integer NOT NULL DEFAULT 0"
return createTable(TableSqlParser.createTable(tableName)
.column(columnDate, Sql.LONG).notNull()
.column(columnTPS, Sql.DOUBLE).notNull()
.column(columnPlayers, Sql.INT).notNull()
.column(columnCPUUsage, Sql.DOUBLE).notNull()
.column(columnRAMUsage, Sql.LONG).notNull()
.column(columnEntities, Sql.INT).notNull()
.column(columnChunksLoaded, Sql.INT).notNull()
.toString()
);
}
@ -97,7 +65,7 @@ public class TPSTable extends Table {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT * FROM " + tableName);
statement = prepareStatement(Select.all(tableName).toString());
set = statement.executeQuery();
while (set.next()) {
long date = set.getLong(columnDate);

View File

@ -50,6 +50,17 @@ public abstract class Table {
*/
public abstract boolean createTable();
protected boolean createTable(String sql) {
try {
execute(sql);
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
}
/**
* @return @throws SQLException
*/

View File

@ -5,6 +5,7 @@ import main.java.com.djrapitops.plan.database.databases.SQLDB;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;
/**
* Represents a Table that uses UsersTable IDs to get their data.
@ -22,6 +23,7 @@ public abstract class UserIDTable extends Table {
usersTable = db.getUsersTable();
}
@Deprecated
protected boolean removeDataOf(int userID) {
PreparedStatement statement = null;
try {
@ -41,4 +43,20 @@ public abstract class UserIDTable extends Table {
close(statement);
}
}
public boolean removeUser(UUID uuid) {
PreparedStatement statement = null;
try {
statement = prepareStatement("DELETE FROM " + tableName +
" WHERE (" + columnUserID + "=" + usersTable.statementSelectID + ")");
statement.setString(1, uuid.toString());
statement.execute();
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
} finally {
close(statement);
}
}
}

View File

@ -0,0 +1,44 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package main.java.com.djrapitops.plan.database.tables;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.Sql;
import main.java.com.djrapitops.plan.database.sql.TableSqlParser;
/**
* //TODO Class Javadoc Comment
*
* @author Rsl1122
*/
public class UserInfoTable extends UserIDTable {
//TODO Server Specific Table
private final String columnUserID = "user_ id";
private final String columnRegistered = "registered";
private final String columnOP = "opped";
private final String columnBanned = "banned";
private final String columnServerID = "server_id";
private final ServerTable serverTable;
public UserInfoTable(SQLDB db, boolean usingMySQL) {
super("plan_user_info", db, usingMySQL);
serverTable = db.getServerTable();
}
@Override
public boolean createTable() {
return createTable(TableSqlParser.createTable(tableName)
.column(columnUserID, Sql.INT).notNull()
.column(columnRegistered, Sql.LONG).notNull()
.column(columnOP, Sql.BOOL).notNull().defaultValue(false)
.column(columnBanned, Sql.BOOL).notNull().defaultValue(false)
.column(columnServerID, Sql.INT).notNull()
.foreignKey(columnUserID, usersTable.getTableName(), usersTable.getColumnID())
.foreignKey(columnServerID, serverTable.getTableName(), serverTable.getColumnID())
.toString());
}
}

View File

@ -1,12 +1,11 @@
package main.java.com.djrapitops.plan.database.tables;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.Select;
import main.java.com.djrapitops.plan.database.sql.Sql;
import main.java.com.djrapitops.plan.database.sql.TableSqlParser;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.database.sql.Update;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@ -16,40 +15,13 @@ import java.util.*;
/**
* @author Rsl1122
*/
public class UsersTable extends Table {
public class UsersTable extends UserIDTable {
private final String columnID = "id";
private final String columnUUID = "uuid";
@Deprecated
private final String columnGeolocation;
@Deprecated
private final String columnLastGM;
@Deprecated
private final String columnLastGMSwapTime;
@Deprecated
private final String columnPlayTime;
@Deprecated
private final String columnLoginTimes;
@Deprecated
private final String columnLastPlayed;
@Deprecated
private final String columnDeaths;
@Deprecated
private final String columnMobKills;
private final String columnRegistered;
private final String columnName;
//TODO Server Specific Table (Also has registered on it)
@Deprecated
private final String columnOP;
@Deprecated
private final String columnBanned;
//
@Deprecated
private final String columnContainsBukkitData;
@Deprecated
private final String columnLastWorldSwapTime;
@Deprecated
private final String columnLastWorld;
private final String columnRegistered = "registered";
private final String columnName = "name";
private final String columnTimesKicked = "times_kicked";
public final String statementSelectID;
@ -60,24 +32,6 @@ public class UsersTable extends Table {
public UsersTable(SQLDB db, boolean usingMySQL) {
super("plan_users", db, usingMySQL);
statementSelectID = "(" + Select.from(tableName, tableName + "." + columnID).where(columnUUID + "=?").toString() + ")";
columnGeolocation = "geolocation";
columnLastGM = "last_gamemode";
columnLastGMSwapTime = "last_gamemode_swap";
columnPlayTime = "play_time";
columnLoginTimes = "login_times";
columnLastPlayed = "last_played";
columnMobKills = "mob_kills";
columnDeaths = "deaths";
columnRegistered = "registered";
columnOP = "opped";
columnName = "name";
columnBanned = "banned";
columnContainsBukkitData = "contains_bukkit_data";
columnLastWorldSwapTime = "last_world_swap";
columnLastWorld = "last_world";
}
/**
@ -85,142 +39,26 @@ public class UsersTable extends Table {
*/
@Override
public boolean createTable() {
try {
execute(TableSqlParser.createTable(tableName)
.primaryKeyIDColumn(usingMySQL, columnID, Sql.INT)
.column(columnUUID, Sql.varchar(36)).notNull().unique()
.column(columnGeolocation, Sql.varchar(50)).notNull()
.column(columnLastGM, Sql.varchar(15)).notNull()
.column(columnLastGMSwapTime, Sql.LONG).notNull()
.column(columnPlayTime, Sql.LONG).notNull()
.column(columnLoginTimes, Sql.INT).notNull()
.column(columnLastPlayed, Sql.LONG).notNull()
.column(columnDeaths, Sql.INT).notNull()
.column(columnMobKills, Sql.INT).notNull()
.column(columnRegistered, Sql.LONG).notNull()
.column(columnOP, Sql.BOOL).notNull().defaultValue(false)
.column(columnName, Sql.varchar(16)).notNull()
.column(columnBanned, Sql.BOOL).notNull().defaultValue(false)
.column(columnContainsBukkitData, Sql.BOOL).notNull().defaultValue(false)
.column(columnLastWorld, Sql.varchar(255)).notNull()
.column(columnLastWorldSwapTime, Sql.LONG).notNull()
.primaryKey(usingMySQL, columnID)
.toString()
);
int version = getVersion();
if (version < 3) {
alterTablesV3();
}
if (version < 4) {
alterTablesV4();
}
if (version < 5) {
alterTablesV5();
}
if (version < 8) {
alterTablesV8();
}
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
}
private void alterTablesV8() {
addColumns(
columnLastWorldSwapTime + " bigint NOT NULL DEFAULT 0",
columnLastWorld + " varchar(255) NOT NULL DEFAULT 'Unknown'"
return createTable(TableSqlParser.createTable(tableName)
.primaryKeyIDColumn(usingMySQL, columnID, Sql.INT)
.column(columnUUID, Sql.varchar(36)).notNull().unique()
.column(columnRegistered, Sql.LONG).notNull()
.column(columnName, Sql.varchar(16)).notNull()
.column(columnTimesKicked, Sql.INT).notNull().defaultValue("0")
.primaryKey(usingMySQL, columnID)
.toString()
);
}
private void alterTablesV5() {
removeColumns("age", "gender");
}
private void alterTablesV4() {
addColumns(
columnContainsBukkitData + " boolean NOT NULL DEFAULT 0",
columnOP + " boolean NOT NULL DEFAULT 0",
columnBanned + " boolean NOT NULL DEFAULT 0",
columnName + " varchar(16) NOT NULL DEFAULT 'Unknown'",
columnRegistered + " bigint NOT NULL DEFAULT 0"
);
}
private void alterTablesV3() {
addColumns(
columnDeaths + " integer NOT NULL DEFAULT 0",
columnMobKills + " integer NOT NULL DEFAULT 0"
);
removeColumns("player_kills");
}
/**
* @param uuid
* @return
* @throws SQLException
*/
public int getUserId(UUID uuid) throws SQLException {
return getUserId(uuid.toString());
}
/**
* @param uuid
* @return
* @throws SQLException
*/
public int getUserId(String uuid) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
int userId = -1;
statement = prepareStatement("SELECT " + columnID + " FROM " + tableName + " WHERE (" + columnUUID + "=?)");
statement.setString(1, uuid);
set = statement.executeQuery();
while (set.next()) {
userId = set.getInt(columnID);
}
return userId;
} finally {
endTransaction(statement);
close(set, statement);
}
}
/**
* @param userID
* @return
* @throws SQLException
*/
public UUID getUserUUID(String userID) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
UUID uuid = null;
statement = prepareStatement("SELECT " + columnUUID + " FROM " + tableName + " WHERE (" + columnID + "=?)");
statement.setString(1, userID);
set = statement.executeQuery();
while (set.next()) {
uuid = UUID.fromString(set.getString(columnUUID));
}
return uuid;
} finally {
endTransaction(statement);
close(set, statement);
}
}
/**
* @return @throws SQLException
*/
public Set<UUID> getSavedUUIDs() throws SQLException {
Benchmark.start("Get Saved UUIDS");
PreparedStatement statement = null;
ResultSet set = null;
try {
Set<UUID> uuids = new HashSet<>();
statement = prepareStatement("SELECT " + columnUUID + " FROM " + tableName);
statement = prepareStatement(Select.from(tableName, columnUUID).toString());
set = statement.executeQuery();
while (set.next()) {
UUID uuid = UUID.fromString(set.getString(columnUUID));
@ -230,7 +68,6 @@ public class UsersTable extends Table {
} finally {
endTransaction(statement);
close(set, statement);
Benchmark.stop("Database", "Get Saved UUIDS");
}
}
@ -238,20 +75,12 @@ public class UsersTable extends Table {
* @param uuid
* @return
*/
@Override
public boolean removeUser(UUID uuid) {
return removeUser(uuid.toString());
}
/**
* @param uuid
* @return
*/
public boolean removeUser(String uuid) {
PreparedStatement statement = null;
try {
statement = prepareStatement("DELETE FROM " + tableName + " WHERE (" + columnUUID + "=?)");
statement.setString(1, uuid);
statement.setString(1, uuid.toString());
statement.execute();
return true;
} catch (SQLException ex) {
@ -266,89 +95,6 @@ public class UsersTable extends Table {
}
}
/**
* @param uuids
* @return
* @throws SQLException
*/
public List<UUID> getContainsBukkitData(Collection<UUID> uuids) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
List<UUID> containsBukkitData = new ArrayList<>();
try {
statement = prepareStatement("SELECT " + columnContainsBukkitData + ", " + columnUUID + " FROM " + tableName);
set = statement.executeQuery();
while (set.next()) {
String uuidS = set.getString(columnUUID);
UUID uuid = UUID.fromString(uuidS);
if (!uuids.contains(uuid)) {
continue;
}
boolean contains = set.getBoolean(columnContainsBukkitData);
if (contains) {
containsBukkitData.add(uuid);
}
}
} finally {
endTransaction(statement);
close(set, statement);
}
return containsBukkitData;
}
/**
* @param uuids
* @return
* @throws SQLException
*/
public Map<UUID, Integer> getUserIds(Collection<UUID> uuids) throws SQLException {
Benchmark.start("Get User IDS Multiple");
PreparedStatement statement = null;
ResultSet set = null;
try {
Map<UUID, Integer> ids = new HashMap<>();
statement = prepareStatement("SELECT " + columnUUID + ", " + columnID + " FROM " + tableName);
set = statement.executeQuery();
while (set.next()) {
String uuidS = set.getString(columnUUID);
UUID uuid = UUID.fromString(uuidS);
if (!uuids.contains(uuid)) {
continue;
}
ids.put(uuid, set.getInt(columnID));
}
return ids;
} finally {
endTransaction(statement);
close(set, statement);
Benchmark.stop("Database", "Get User IDS Multiple");
}
}
/**
* @return @throws SQLException
*/
public Map<UUID, Integer> getAllUserIds() throws SQLException {
Benchmark.start("Get User IDS ALL");
PreparedStatement statement = null;
ResultSet set = null;
try {
Map<UUID, Integer> ids = new HashMap<>();
statement = prepareStatement("SELECT " + columnUUID + ", " + columnID + " FROM " + tableName);
set = statement.executeQuery();
while (set.next()) {
String uuidS = set.getString(columnUUID);
UUID uuid = UUID.fromString(uuidS);
ids.put(uuid, set.getInt(columnID));
}
return ids;
} finally {
endTransaction(statement);
close(set, statement);
Benchmark.stop("Database", "Get User IDS ALL");
}
}
/**
* @return
*/
@ -356,6 +102,10 @@ public class UsersTable extends Table {
return columnID;
}
public String getColumnUUID() {
return columnUUID;
}
/**
* @param playername
* @return
@ -365,7 +115,9 @@ public class UsersTable extends Table {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT " + columnUUID + " FROM " + tableName + " WHERE (UPPER(" + columnName + ")=UPPER(?))");
statement = prepareStatement(Select.from(tableName, columnUUID)
.where("UPPER(" + columnName + ")=UPPER(?)")
.toString());
statement.setString(1, playername);
set = statement.executeQuery();
if (set.next()) {
@ -379,8 +131,111 @@ public class UsersTable extends Table {
}
}
public List<UserData> getUserData(List<UUID> uuids) {
// TODO Rewrite method for new UserData objects.
return new ArrayList<>();
public List<Long> getRegisterDates() throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement(Select.from(tableName, columnRegistered).toString());
set = statement.executeQuery();
List<Long> registerDates = new ArrayList<>();
while (set.next()) {
registerDates.add(set.getLong(columnRegistered));
}
return registerDates;
} finally {
endTransaction(statement);
close(set, statement);
}
}
/**
* Register a new user (UUID) to the database.
*
* @param uuid UUID of the player.
* @param registered Register date.
* @param name Name of the player.
* @throws SQLException
* @throws IllegalArgumentException If uuid or name are null.
*/
public void registerUser(UUID uuid, long registered, String name) throws SQLException {
Verify.nullCheck(uuid, name);
PreparedStatement statement = null;
try {
statement = prepareStatement(Insert.values(tableName,
columnUUID,
columnRegistered,
columnName));
statement.setString(1, uuid.toString());
statement.setLong(2, registered);
statement.setString(3, name);
statement.execute();
} finally {
close(statement);
}
}
public boolean isRegistered(UUID uuid) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement(Select.from(tableName, columnID)
.where(columnUUID + "=?")
.toString());
statement.setString(1, uuid.toString());
set = statement.executeQuery();
return set.next();
} finally {
endTransaction(statement);
close(set, statement);
}
}
public void updateName(UUID uuid, String name) throws SQLException {
PreparedStatement statement = null;
try {
statement = prepareStatement(Update.values(tableName, columnName)
.where(columnUUID + "=?")
.toString());
statement.setString(1, name);
statement.setString(2, uuid.toString());
statement.execute();
} finally {
endTransaction(statement);
close(statement);
}
}
public int getTimesKicked(UUID uuid) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement(Select.from(tableName, columnTimesKicked)
.where(columnUUID + "=?")
.toString());
statement.setString(1, uuid.toString());
set = statement.executeQuery();
if (set.next()) {
return set.getInt(columnTimesKicked);
}
return 0;
} finally {
endTransaction(statement);
close(set, statement);
}
}
public void kicked(UUID uuid) throws SQLException {
PreparedStatement statement = null;
try {
statement = prepareStatement(Update.values(tableName, columnTimesKicked)
.where(columnUUID + "=?")
.toString());
statement.setInt(1, getTimesKicked(uuid) + 1);
statement.setString(2, uuid.toString());
statement.execute();
} finally {
close(statement);
}
}
}

View File

@ -27,16 +27,10 @@ public class VersionTable extends Table {
*/
@Override
public boolean createTable() {
try {
execute(TableSqlParser.createTable(tableName)
.column("version", Sql.INT).notNull()
.toString()
);
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
return createTable(TableSqlParser.createTable(tableName)
.column("version", Sql.INT).notNull()
.toString()
);
}
/**

View File

@ -1,7 +1,6 @@
package main.java.com.djrapitops.plan.database.tables;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.Sql;
import main.java.com.djrapitops.plan.database.sql.TableSqlParser;
@ -23,9 +22,11 @@ import java.util.List;
*/
public class WorldTable extends Table {
private final String columnWorldId;
private final String columnWorldName;
private final String columnServerID; //TODO
private final String columnWorldId = "id";
private final String columnWorldName = "world_name";
private final String columnServerID = "server_id";
public final String statementSelectID;
/**
* Constructor.
@ -35,25 +36,17 @@ public class WorldTable extends Table {
*/
public WorldTable(SQLDB db, boolean usingMySQL) {
super("plan_worlds", db, usingMySQL);
columnWorldId = "world_id";
columnWorldName = "world_name";
columnServerID = "server_id";
statementSelectID = "(SELECT " + columnWorldId + " FROM " + tableName + " WHERE (" + columnWorldName + "=?))";
}
@Override
public boolean createTable() {
try {
execute(TableSqlParser.createTable(tableName)
.primaryKeyIDColumn(usingMySQL, columnWorldId, Sql.INT)
.column(columnWorldName, Sql.varchar(100)).notNull()
.primaryKey(usingMySQL, columnWorldId)
.toString()
);
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
}
return createTable(TableSqlParser.createTable(tableName)
.primaryKeyIDColumn(usingMySQL, columnWorldId, Sql.INT)
.column(columnWorldName, Sql.varchar(100)).notNull()
.primaryKey(usingMySQL, columnWorldId)
.toString()
);
}
/**

View File

@ -1,7 +1,8 @@
package main.java.com.djrapitops.plan.database.tables;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.data.time.GMTimes;
import main.java.com.djrapitops.plan.data.time.WorldTimes;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.Sql;
@ -10,29 +11,27 @@ import main.java.com.djrapitops.plan.database.sql.TableSqlParser;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* Table class representing database table plan_world_times.
*
* @author Rsl1122
* @since 3.6.0 / Database version 7
* @since 4.0.0
*/
public class WorldTimesTable extends UserIDTable {
private final String columnServerID = "server_id"; //TODO
private final WorldTable worldTable;
private final String worldIDColumn;
private final String worldNameColumn;
private final String columnSessionID = "session_id";
private final String columnWorldId = "world_id";
@Deprecated
private final String columnPlaytime = "playtime";
//TODO GM Times to World table
private final String columnSurvival = "survival_time";
private final String columnCreative = "creative_time";
private final String columnAdventure = "adventure_time";
private final String columnSpectator = "spectator_time";
private final String selectWorldIDsql;
private final WorldTable worldTable;
private final SessionsTable sessionsTable;
/**
* Constructor.
@ -43,266 +42,111 @@ public class WorldTimesTable extends UserIDTable {
public WorldTimesTable(SQLDB db, boolean usingMySQL) {
super("plan_world_times", db, usingMySQL);
worldTable = db.getWorldTable();
worldIDColumn = worldTable + "." + worldTable.getColumnID();
worldNameColumn = worldTable.getColumnWorldName();
selectWorldIDsql = "(SELECT " + worldIDColumn + " FROM " + worldTable + " WHERE (" + worldNameColumn + "=?))";
sessionsTable = db.getSessionsTable();
}
@Override
public boolean createTable() {
UsersTable usersTable = db.getUsersTable();
try {
execute(TableSqlParser.createTable(tableName)
.column(columnUserID, Sql.INT).notNull()
.column(columnWorldId, Sql.INT).notNull()
.column(columnPlaytime, Sql.LONG).notNull()
.foreignKey(columnUserID, usersTable.getTableName(), usersTable.getColumnID())
.foreignKey(columnWorldId, worldTable.getTableName(), worldTable.getColumnID())
.toString()
);
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
return createTable(TableSqlParser.createTable(tableName)
.column(columnUserID, Sql.INT).notNull()
.column(columnWorldId, Sql.INT).notNull()
.column(columnSessionID, Sql.LONG).notNull()
.column(columnSurvival, Sql.LONG).notNull().defaultValue("0")
.column(columnCreative, Sql.LONG).notNull().defaultValue("0")
.column(columnAdventure, Sql.LONG).notNull().defaultValue("0")
.column(columnSpectator, Sql.LONG).notNull().defaultValue("0")
.foreignKey(columnUserID, usersTable.getTableName(), usersTable.getColumnID())
.foreignKey(columnWorldId, worldTable.getTableName(), worldTable.getColumnID())
.foreignKey(columnSessionID, sessionsTable.getTableName(), sessionsTable.getColumnID())
.toString()
);
}
public void saveWorldTimes(UUID uuid, long sessionID, WorldTimes worldTimes) throws SQLException {
if (Verify.isEmpty(worldTimes.getWorldTimes())) {
return;
}
}
public boolean removeUserWorldTimes(int userId) {
return super.removeDataOf(userId);
}
/**
* @param userId
* @return
* @throws SQLException
*/
public Map<String, Long> getWorldTimes(int userId) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT "
+ columnPlaytime + ", "
+ worldNameColumn
+ " FROM " + tableName + ", " + worldTable
+ " WHERE (" + columnUserID + "=?)"
+ " AND (" + worldIDColumn + "=" + tableName + "." + columnWorldId + ")");
statement.setInt(1, userId);
set = statement.executeQuery();
HashMap<String, Long> times = new HashMap<>();
while (set.next()) {
times.put(set.getString(worldNameColumn), set.getLong(columnPlaytime));
statement = prepareStatement("INSERT INTO " + tableName + " (" +
columnUserID + ", " +
columnWorldId + ", " +
columnSessionID + ", " +
columnSurvival + ", " +
columnCreative + ", " +
columnAdventure + ", " +
columnSpectator +
") VALUES (" +
usersTable.statementSelectID + ", " +
worldTable.statementSelectID + ", " +
"?, ?, ?, ?, ?)");
for (Map.Entry<String, GMTimes> entry : worldTimes.getWorldTimes().entrySet()) {
String worldName = entry.getKey();
GMTimes gmTimes = entry.getValue();
statement.setString(1, uuid.toString());
statement.setString(2, worldName);
statement.setLong(3, sessionID);
String[] gms = GMTimes.getGMKeyArray();
statement.setLong(4, gmTimes.getTime(gms[0]));
statement.setLong(5, gmTimes.getTime(gms[1]));
statement.setLong(6, gmTimes.getTime(gms[2]));
statement.setLong(7, gmTimes.getTime(gms[3]));
statement.addBatch();
}
return times;
statement.executeBatch();
} finally {
endTransaction(statement);
close(set, statement);
close(statement);
}
}
public Map<Integer, Map<String, Long>> getWorldTimes(Collection<Integer> userIds) throws SQLException {
public void addWorldTimesToSessions(UUID uuid, Map<Long, Session> sessions) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
Map<Integer, Map<String, Long>> times = new HashMap<>();
for (Integer id : userIds) {
times.put(id, new HashMap<>());
}
try {
statement = prepareStatement("SELECT "
+ columnUserID + ", "
+ columnPlaytime + ", "
+ worldNameColumn
+ " FROM " + tableName + ", " + worldTable
+ " WHERE (" + worldIDColumn + "=" + tableName + "." + columnWorldId + ")");
String worldIDColumn = worldTable + "." + worldTable.getColumnID();
String worldNameColumn = worldTable + "." + worldTable.getColumnWorldName() + " as world_name";
statement = prepareStatement("SELECT " +
columnSessionID + ", " +
columnSurvival + ", " +
columnCreative + ", " +
columnAdventure + ", " +
columnSpectator + ", " +
worldNameColumn +
" FROM " + tableName +
" WHERE " + columnUserID + "=" + usersTable.statementSelectID +
" JOIN " + worldTable + " on " + worldIDColumn + "=" + columnWorldId // TODO TEST
);
statement.setString(1, uuid.toString());
set = statement.executeQuery();
String[] gms = GMTimes.getGMKeyArray();
while (set.next()) {
int id = set.getInt(columnUserID);
if (!userIds.contains(id)) {
long sessionID = set.getLong(columnSessionID);
Session session = sessions.get(sessionID);
if (session == null) {
continue;
}
Map<String, Long> worldTimes = times.get(id);
worldTimes.put(set.getString(worldNameColumn), set.getLong(columnPlaytime));
String worldName = set.getString("world_name");
Map<String, Long> gmMap = new HashMap<>();
gmMap.put(gms[0], set.getLong(columnSurvival));
gmMap.put(gms[1], set.getLong(columnCreative));
gmMap.put(gms[2], set.getLong(columnAdventure));
gmMap.put(gms[3], set.getLong(columnSpectator));
GMTimes gmTimes = new GMTimes(gmMap);
session.getWorldTimes().setGMTimesForWorld(worldName, gmTimes);
}
return times;
} finally {
endTransaction(statement);
close(set, statement);
}
}
public void saveWorldTimes(int userId, Map<String, Long> worldTimes) throws SQLException {
if (Verify.isEmpty(worldTimes)) {
return;
}
Map<String, Long> saved = getWorldTimes(userId);
Map<String, Long> newData = new HashMap<>();
Map<String, Long> updateData = new HashMap<>();
for (Map.Entry<String, Long> entry : worldTimes.entrySet()) {
String world = entry.getKey();
long time = entry.getValue();
Long savedTime = saved.get(world);
if (savedTime == null) {
newData.put(world, time);
} else {
if (savedTime < time) {
updateData.put(world, time);
}
}
}
insertWorlds(userId, newData);
updateWorlds(userId, updateData);
}
private void updateWorlds(int userId, Map<String, Long> updateData) throws SQLException {
if (Verify.isEmpty(updateData)) {
return;
}
PreparedStatement statement = null;
try {
statement = prepareStatement(
"UPDATE " + tableName + " SET " + columnPlaytime + "=?" +
" WHERE (" + selectWorldIDsql + "=" + columnWorldId + ")" +
" AND (" + columnUserID + "=?)"
);
for (Map.Entry<String, Long> entry : updateData.entrySet()) {
String worldName = entry.getKey();
long time = entry.getValue();
statement.setLong(1, time);
statement.setString(2, worldName);
statement.setInt(3, userId);
statement.addBatch();
}
statement.executeBatch();
} finally {
endTransaction(statement);
close(statement);
}
}
private void insertWorlds(int userId, Map<String, Long> newData) throws SQLException {
if (Verify.isEmpty(newData)) {
return;
}
PreparedStatement statement = null;
try {
statement = prepareStatement(
"INSERT INTO " + tableName + " ("
+ columnUserID + ", "
+ columnWorldId + ", "
+ columnPlaytime
+ ") VALUES (?, " + selectWorldIDsql + ", ?)"
);
for (Map.Entry<String, Long> entry : newData.entrySet()) {
String worldName = entry.getKey();
long time = entry.getValue();
statement.setInt(1, userId);
statement.setString(2, worldName);
statement.setLong(3, time);
statement.addBatch();
}
statement.executeBatch();
} finally {
endTransaction(statement);
close(statement);
}
}
public void saveWorldTimes(Map<Integer, Map<String, Long>> worldTimesMultiple) throws SQLException {
if (Verify.isEmpty(worldTimesMultiple)) {
return;
}
Map<Integer, Map<String, Long>> saved = getWorldTimes(worldTimesMultiple.keySet());
Map<Integer, Map<String, Long>> newData = new HashMap<>();
Map<Integer, Map<String, Long>> updateData = new HashMap<>();
for (Map.Entry<Integer, Map<String, Long>> entry : worldTimesMultiple.entrySet()) {
int userId = entry.getKey();
Map<String, Long> savedTimes = saved.get(userId);
Map<String, Long> worldTimes = entry.getValue();
Map<String, Long> newTimes = new HashMap<>(worldTimes);
newTimes.keySet().removeAll(savedTimes.keySet());
newData.put(userId, newTimes);
for (Map.Entry<String, Long> times : savedTimes.entrySet()) {
String world = times.getKey();
long savedTime = times.getValue();
Long toSave = worldTimes.get(world);
if (toSave != null && toSave <= savedTime) {
worldTimes.remove(world);
}
}
updateData.put(userId, worldTimes);
}
insertWorlds(newData);
updateWorlds(updateData);
}
private void updateWorlds(Map<Integer, Map<String, Long>> updateData) throws SQLException {
if (Verify.isEmpty(updateData)) {
return;
}
PreparedStatement statement = null;
try {
statement = prepareStatement(
"UPDATE " + tableName + " SET " + columnPlaytime + "=?" +
" WHERE (" + selectWorldIDsql + "=" + columnWorldId + ")" +
" AND (" + columnUserID + "=?)"
);
for (Map.Entry<Integer, Map<String, Long>> entry : updateData.entrySet()) {
int userId = entry.getKey();
for (Map.Entry<String, Long> times : entry.getValue().entrySet()) {
String worldName = times.getKey();
long time = times.getValue();
statement.setLong(1, time);
statement.setString(2, worldName);
statement.setInt(3, userId);
statement.addBatch();
}
}
statement.executeBatch();
} finally {
endTransaction(statement);
close(statement);
}
}
private void insertWorlds(Map<Integer, Map<String, Long>> newData) throws SQLException {
if (Verify.isEmpty(newData)) {
return;
}
PreparedStatement statement = null;
try {
statement = prepareStatement(
"INSERT INTO " + tableName + " ("
+ columnUserID + ", "
+ columnWorldId + ", "
+ columnPlaytime
+ ") VALUES (?, " + selectWorldIDsql + ", ?)"
);
for (Map.Entry<Integer, Map<String, Long>> entry : newData.entrySet()) {
int userId = entry.getKey();
for (Map.Entry<String, Long> times : entry.getValue().entrySet()) {
String worldName = times.getKey();
long time = times.getValue();
statement.setInt(1, userId);
statement.setString(2, worldName);
statement.setLong(3, time);
statement.addBatch();
}
}
statement.executeBatch();
} finally {
endTransaction(statement);
close(statement);
}
}
public void saveWorldTimes(WorldTimes worldTimes) {
// TODO saveWorldTimes (INSERT)
}
}

View File

@ -1,5 +1,6 @@
package main.java.com.djrapitops.plan.queue.processing;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.queue.Consumer;
import main.java.com.djrapitops.plan.queue.Queue;
import main.java.com.djrapitops.plan.queue.Setup;
@ -47,7 +48,11 @@ class ProcessConsumer extends Consumer<Processor> {
if (process == null) {
return;
}
process.process();
try {
process.process();
} catch (Exception | NoClassDefFoundError | NoSuchFieldError | NoSuchMethodError e) {
Log.toLog(this.getTaskName() + ":" + process.getClass().getSimpleName(), e);
}
}
@Override

View File

@ -298,7 +298,7 @@ public class Analysis {
activity.addBan(uuid);
} else if (uData.getLoginTimes() == 1) {
activity.addJoinedOnce(uuid);
// TODO } else if (AnalysisUtils.isActive(now, uData.getLastPlayed(), playTime, uData.getLoginTimes())) {
// TODO } else if (AnalysisUtils.isActive(now, uData.getLastPlayed(), playTime, uData.getSessionCount())) {
// activity.addActive(uuid);
} else {
activity.addInActive(uuid);

View File

@ -32,7 +32,6 @@ public class SessionCacheTest {
@Before
public void setUp() throws Exception {
TestInit.init();
test = new SessionCache();
}
@Test