Merge branch '4.0.0-Connection-Pool-Branch' of https://github.com/Rsl1122/Plan-PlayerAnalytics into 4.0.0-Connection-Pool-Branch

# Conflicts:
#	Plan/test/test/java/main/java/com/djrapitops/plan/database/DatabaseTest.java
#	Plan/test/test/java/utils/TestInit.java
This commit is contained in:
Rsl1122 2017-08-23 22:16:12 +03:00
commit b4abc6a776
49 changed files with 1133 additions and 947 deletions

View File

@ -29,9 +29,7 @@ import main.java.com.djrapitops.plan.api.API;
import main.java.com.djrapitops.plan.command.PlanCommand;
import main.java.com.djrapitops.plan.command.commands.RegisterCommandFilter;
import main.java.com.djrapitops.plan.data.additional.HookHandler;
import main.java.com.djrapitops.plan.data.cache.AnalysisCacheHandler;
import main.java.com.djrapitops.plan.data.cache.DataCache;
import main.java.com.djrapitops.plan.data.cache.InspectCacheHandler;
import main.java.com.djrapitops.plan.data.cache.PageCacheHandler;
import main.java.com.djrapitops.plan.data.listeners.*;
import main.java.com.djrapitops.plan.data.server.ServerInfoManager;
@ -46,7 +44,6 @@ import main.java.com.djrapitops.plan.ui.webserver.WebServer;
import main.java.com.djrapitops.plan.ui.webserver.api.bukkit.*;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.webserver.api.WebAPIManager;
import org.apache.logging.log4j.LogManager;
import org.bukkit.ChatColor;
@ -70,8 +67,6 @@ public class Plan extends BukkitPlugin<Plan> {
private ProcessingQueue processingQueue;
private DataCache dataCache;
private InspectCacheHandler inspectCache;
private AnalysisCacheHandler analysisCache;
private HookHandler hookHandler; // Manages 3rd party data sources
private Database db;
@ -158,8 +153,6 @@ public class Plan extends BukkitPlugin<Plan> {
Benchmark.start("Init DataCache");
this.dataCache = new DataCache(this);
this.inspectCache = new InspectCacheHandler(this);
this.analysisCache = new AnalysisCacheHandler(this);
Benchmark.stop("Enable", "Init DataCache");
tpsCountTimer = new TPSCountTimer(this);
@ -331,8 +324,9 @@ public class Plan extends BukkitPlugin<Plan> {
@Override
public void run() {
Log.debug("Running PeriodicalAnalysisTask");
if (!analysisCache.isCached() || MiscUtils.getTime() - analysisCache.getData().getRefreshDate() > TimeAmount.MINUTE.ms()) {
analysisCache.updateCache();
// TODO DataCacheMethod for checking analysis refresh date.
if (true) {
// TODO analysisCache.updateCache();
}
}
}).runTaskTimerAsynchronously(everyXMinutes * TimeAmount.MINUTE.ticks(), everyXMinutes * TimeAmount.MINUTE.ticks());
@ -352,7 +346,7 @@ public class Plan extends BukkitPlugin<Plan> {
Log.debug("Running BootAnalysisTask");
Log.info(bootAnalysisRunMsg);
analysisCache.updateCache();
//TODO analysisCache.updateCache();
this.cancel();
}
}).runTaskLaterAsynchronously(30 * TimeAmount.SECOND.ticks());
@ -368,24 +362,6 @@ public class Plan extends BukkitPlugin<Plan> {
logger.addFilter(new RegisterCommandFilter());
}
/**
* Used to access AnalysisCache.
*
* @return Current instance of the AnalysisCacheHandler
*/
public AnalysisCacheHandler getAnalysisCache() {
return analysisCache;
}
/**
* Used to access InspectCache.
*
* @return Current instance of the InspectCacheHandler
*/
public InspectCacheHandler getInspectCache() {
return inspectCache;
}
/**
* Used to access Cache.
*
@ -478,6 +454,6 @@ public class Plan extends BukkitPlugin<Plan> {
}
public static UUID getServerUUID() {
return getInstance().serverInfoManager.getServerUUID();
return getInstance().getServerInfoManager().getServerUUID();
}
}

View File

@ -5,10 +5,8 @@ import com.djrapitops.plugin.utilities.player.Fetch;
import com.djrapitops.plugin.utilities.player.IOfflinePlayer;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.AnalysisData;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.additional.AnalysisType;
import main.java.com.djrapitops.plan.data.additional.PluginData;
import main.java.com.djrapitops.plan.data.cache.DBCallableProcessor;
import main.java.com.djrapitops.plan.ui.html.DataRequestHandler;
import main.java.com.djrapitops.plan.ui.webserver.WebServer;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
@ -16,11 +14,7 @@ import main.java.com.djrapitops.plan.utilities.uuid.UUIDUtility;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* This class contains the API methods.
@ -35,7 +29,6 @@ import java.util.stream.Collectors;
* @author Rsl1122
* @see PluginData
* @see AnalysisType
* @see DBCallableProcessor
* @since 2.0.0
*/
public class API {
@ -94,18 +87,19 @@ public class API {
}
/**
* Check if the UserData is cached to the InspectCache.
* Check if the UserInfo is cached to the InspectCache.
*
* @param uuid UUID of the player.
* @return true/false
*/
@Deprecated
public boolean isPlayersDataInspectCached(UUID uuid) {
return plugin.getInspectCache().isCached(uuid);
// TODO Check PageCache
return false;
}
/**
* Cache the UserData to InspectCache.
* Cache the UserInfo to InspectCache.
* <p>
* Uses cache if data is cached or database if not. Call from an Asynchronous
* thread.
@ -114,7 +108,7 @@ public class API {
*/
@Deprecated
public void cacheUserDataToInspectCache(UUID uuid) {
plugin.getInspectCache().cache(uuid);
// TODO Run Inspect parse
}
/**
@ -140,7 +134,8 @@ public class API {
* @return true/false
*/
public boolean isAnalysisCached() {
return plugin.getAnalysisCache().isCached();
// TODO Check PageCache
return false;
}
/**
@ -150,7 +145,7 @@ public class API {
* Starts a new Asynchronous task to run the analysis.
*/
public void updateAnalysisCache() {
plugin.getAnalysisCache().updateCache();
// TODO Run analysis
}
/**
@ -178,7 +173,8 @@ public class API {
* @see AnalysisData
*/
public AnalysisData getAnalysisDataFromCache() {
return plugin.getAnalysisCache().getData();
// TODO Fix
return null;
}
/**
@ -239,49 +235,4 @@ public class API {
public Collection<UUID> getSavedUUIDs() throws SQLException {
return plugin.getDB().getSavedUUIDs();
}
/**
* Get the saved UserData in the database for a collection of UUIDs.
* <p>
* Will not contain data for UUIDs not found in the database.
* <p>
* Should be called from async thread.
*
* @param uuids Collection of UUIDs that can be found in the database.
* @return List of all Data in the database.
* @throws SQLException If database error occurs.
* @since 3.4.2
*/
public List<UserData> getUserDataOfUsers(Collection<UUID> uuids) throws SQLException {
return plugin.getDB().getUserDataForUUIDS(uuids);
}
/**
* Get the cached UserData objects in the InspectCache.
* <p>
* This can be used with PluginData objects safely to get the data for all
* users in Plan database, because all data is InspectCached before analysis
* begins.
*
* @return List of all Data in the InspectCache.
* @since 3.5.0
*/
public List<UserData> getInspectCachedUserData() {
return plugin.getInspectCache().getCachedUserData();
}
/**
* Get the cached UserData objects in the InspectCache in a Map form.
* <p>
* This can be used with PluginData objects safely to get the data for all
* users in Plan database, because all data is InspectCached before analysis
* begins.
*
* @return Map of all Data in the InspectCache with UUID of the player as
* the key.
* @since 3.5.0
*/
public Map<UUID, UserData> getInspectCachedUserDataMap() {
return getInspectCachedUserData().stream().collect(Collectors.toMap(UserData::getUuid, Function.identity()));
}
}

View File

@ -1,6 +1,5 @@
package main.java.com.djrapitops.plan.command.commands;
import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.CommandUtils;
import com.djrapitops.plugin.command.ISender;
@ -10,11 +9,9 @@ import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.command.ConditionUtils;
import main.java.com.djrapitops.plan.data.cache.AnalysisCacheHandler;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import org.bukkit.ChatColor;
/**
@ -26,7 +23,6 @@ import org.bukkit.ChatColor;
public class AnalyzeCommand extends SubCommand {
private final Plan plugin;
private final AnalysisCacheHandler analysisCache;
/**
* Subcommand Constructor.
@ -39,7 +35,6 @@ public class AnalyzeCommand extends SubCommand {
Permissions.ANALYZE.getPermission(),
Locale.get(Msg.CMD_USG_ANALYZE).parse());
this.plugin = plugin;
analysisCache = plugin.getAnalysisCache();
}
@Override
@ -53,10 +48,11 @@ public class AnalyzeCommand extends SubCommand {
return true;
}
if (!Check.isTrue(analysisCache.isAnalysisEnabled(), Locale.get(Msg.CMD_INFO_ANALYSIS_TEMP_DISABLE).toString(), sender)
&& !analysisCache.isCached()) {
return true;
}
// TODO Check if analysis is enabled.
// if (!Check.isTrue(analysisCache.isAnalysisEnabled(), Locale.get(Msg.CMD_INFO_ANALYSIS_TEMP_DISABLE).toString(), sender)
// && !analysisCache.isCached()) {
// return true;
// }
sender.sendMessage(Locale.get(Msg.CMD_INFO_FETCH_DATA).toString());
if (plugin.getUiServer().isAuthRequired() && CommandUtils.isPlayer(sender)) {
@ -81,15 +77,16 @@ public class AnalyzeCommand extends SubCommand {
}
private void updateCache(ISender sender) {
if (!analysisCache.isCached() || MiscUtils.getTime() - analysisCache.getData().getRefreshDate() > TimeAmount.MINUTE.ms()) {
int bootAnID = plugin.getBootAnalysisTaskID();
if (bootAnID != -1) {
plugin.getServer().getScheduler().cancelTask(bootAnID);
}
analysisCache.addNotification(sender);
analysisCache.updateCache();
} else {
analysisCache.sendAnalysisMessage(sender);
}
// TODO
// if (!analysisCache.isCached() || MiscUtils.getTime() - analysisCache.getData().getRefreshDate() > TimeAmount.MINUTE.ms()) {
// int bootAnID = plugin.getBootAnalysisTaskID();
// if (bootAnID != -1) {
// plugin.getServer().getScheduler().cancelTask(bootAnID);
// }
// analysisCache.addNotification(sender);
// analysisCache.updateCache();
// } else {
// analysisCache.sendAnalysisMessage(sender);
// }
}
}

View File

@ -11,7 +11,6 @@ import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.command.ConditionUtils;
import main.java.com.djrapitops.plan.data.cache.InspectCacheHandler;
import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.Check;
@ -24,7 +23,7 @@ import java.sql.SQLException;
import java.util.UUID;
/**
* This command is used to cache UserData to InspectCache and display the link.
* This command is used to cache UserInfo to InspectCache and display the link.
*
* @author Rsl1122
* @since 1.0.0
@ -32,7 +31,6 @@ import java.util.UUID;
public class InspectCommand extends SubCommand {
private final Plan plugin;
private final InspectCacheHandler inspectCache;
/**
* Class Constructor.
@ -47,7 +45,6 @@ public class InspectCommand extends SubCommand {
"<player>");
this.plugin = plugin;
inspectCache = plugin.getInspectCache();
}
@ -90,7 +87,7 @@ public class InspectCommand extends SubCommand {
sender.sendMessage(ChatColor.YELLOW + "[Plan] You might not have a web user, use /plan register <password>");
}
}
inspectCache.cache(uuid);
//TODO Inspect Request.
runMessageSenderTask(uuid, sender, playerName);
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
@ -108,11 +105,7 @@ public class InspectCommand extends SubCommand {
@Override
public void run() {
timesrun++;
if (inspectCache.isCached(uuid)) {
sendInspectMsg(sender, playerName, uuid);
this.cancel();
return;
}
// TODO better message sending.
if (timesrun > 10) {
Log.debug("Command Timeout Message, Inspect.");
sender.sendMessage(Locale.get(Msg.CMD_FAIL_TIMEOUT).parse("Inspect"));

View File

@ -4,6 +4,7 @@
*/
package main.java.com.djrapitops.plan.data;
import com.google.common.base.Objects;
import main.java.com.djrapitops.plan.database.tables.Actions;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.utilities.FormatUtils;
@ -57,4 +58,20 @@ public class Action {
public String toString() {
return Html.TABLELINE_3.parse(FormatUtils.formatTimeStampYear(date), doneAction.toString(), additionalInfo);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Action action = (Action) o;
return date == action.date &&
serverID == action.serverID &&
doneAction == action.doneAction &&
Objects.equal(additionalInfo, action.additionalInfo);
}
@Override
public int hashCode() {
return Objects.hashCode(date, doneAction, additionalInfo, serverID);
}
}

View File

@ -6,7 +6,7 @@ import java.util.Objects;
import java.util.UUID;
/**
* This class is used to store data about a player kill inside the UserData
* This class is used to store data about a player kill inside the UserInfo
* object.
*
* @author Rsl1122

View File

@ -1,217 +0,0 @@
package main.java.com.djrapitops.plan.data;
import java.net.InetAddress;
import java.util.*;
/**
* This class is used for storing information about a player during runtime.
*
* @author Rsl1122
*/
// TODO Change to be only used for DB User Get Query responses.
public class UserData {
private final List<Session> sessions;
private int accessing;
private boolean clearAfterSave;
private UUID uuid;
private String name; //TODO DB Update code to JoinListener
@Deprecated
private Set<String> nicknames; //TODO DB Update code to ChatListener
@Deprecated
private String lastNick; //TODO DB Update code to ChatListener
@Deprecated
private String geolocation; //TODO DB Update code to JoinListener
@Deprecated
private Set<InetAddress> ips; //TODO DB Update code to JoinListener
@Deprecated
private int timesKicked; //TODO DB Update code to KickListener
@Deprecated
private boolean isOp; //TODO DB Update code to JoinListener
@Deprecated
private boolean isBanned; //TODO DB Update code to JoinListener
@Deprecated
private long registered; //TODO DB Update code to JoinListener (When registering)
@Deprecated
private long lastPlayed; //TODO DB Update code to Join, Refresh, QuitListener
/**
* Creates a new UserData object with given values and default values.
* <p>
* Some variables are left uninitialized: isBanned, lastPlayed, playTime,
* loginTimes, timesKicked, lastGmSwapTime, mobKills, deaths, lastWorldSwapTime, lastWorld
* <p>
* These variables need to be set with setters.
* <p>
* All Collections are left empty: locations, nicknames, ips, sessions,
* playerKills. Because nicknames is empty, lastNick is an empty string.
* <p>
* gmTimes Map will contain 4 '0L' values: SURVIVAL, CREATIVE,
* ADVENTURE, SPECTATOR
* worldTimes Map is left empty.
*
* @param uuid UUID of the player
* @param name Name of the player.
*/
public UserData(UUID uuid, String name) {
this.uuid = uuid;
this.name = name;
sessions = new ArrayList<>();
}
/**
* Creates a new UserData object with copied values.
*
* @param data UserData to copy into the new object.
*/
public UserData(UserData data) {
this.uuid = data.getUuid();
this.name = data.getName();
this.sessions = new ArrayList<>();
sessions.addAll(data.getSessions());
}
/**
* Used to get the UUID of the player.
*
* @return UUID.
*/
public UUID getUuid() {
return uuid;
}
/**
* Get the InetAddress Set.
*
* @return a HashSet of ips.
*/
public Set<InetAddress> getIps() {
return ips;
}
/**
* Get the nickname String Set.
*
* @return a HashSet of Strings.
*/
public Set<String> getNicknames() {
return nicknames;
}
/**
* Get the Epoch millisecond the player registered.
*
* @return long in ms.
*/
public long getRegistered() {
return registered;
}
/**
* Get the Epoch millisecond the player was last seen.
* <p>
* NOT INITIALIZED BY CONSTRUCTORS. Value is updated periodically by cache
* if the player is online.
*
* @return long in ms.
*/
public long getLastPlayed() {
return lastPlayed;
}
/**
* Get how many times the player has logged in.
* <p>
* NOT INITIALIZED BY CONSTRUCTORS.
*
* @return 0 to Integer.MAX
*/
public int getLoginTimes() {
return sessions.size();
}
/**
* Get how many times the player has been kicked.
* <p>
* NOT INITIALIZED BY CONSTRUCTORS.
*
* @return 0 to Integer.MAX
*/
public int getTimesKicked() {
return timesKicked;
}
/**
* Is the user Operator?
*
* @return opped?
*/
public boolean isOp() {
return isOp;
}
/**
* Is the user Banned?
*
* @return banned?
*/
public boolean isBanned() {
return isBanned;
}
/**
* Get the username of the player.
*
* @return username.
*/
public String getName() {
return name;
}
/**
* Get the sessions of a player.
*
* @return a list of Session.
*/
public List<Session> getSessions() {
return sessions;
}
@Override
public int hashCode() {
int result = sessions.hashCode();
result = 31 * result + accessing;
result = 31 * result + (clearAfterSave ? 1 : 0);
result = 31 * result + uuid.hashCode();
result = 31 * result + name.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UserData other = (UserData) obj;
return Objects.equals(this.name, other.name)
&& Objects.equals(this.uuid, other.uuid)
&& Objects.equals(this.sessions, other.sessions);
}
public long getPlayTime() {
return 0; //TODO Use Sessions
}
public List<String> getGeolocations() {
// TODO
return null;
}
}

View File

@ -0,0 +1,90 @@
package main.java.com.djrapitops.plan.data;
import com.google.common.base.Objects;
import java.util.UUID;
/**
* Used for storing information of players after it has been fetched.
*
* @author Rsl1122
*/
public class UserInfo {
private final UUID uuid;
private String name;
private long registered;
private long lastSeen;
private boolean banned;
private boolean opped;
public UserInfo(UUID uuid) {
this.uuid = uuid;
}
public UserInfo(UUID uuid, String name, long registered, boolean opped, boolean banned) {
this.uuid = uuid;
this.name = name;
this.registered = registered;
this.opped = opped;
this.banned = banned;
}
public UUID getUuid() {
return uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getRegistered() {
return registered;
}
public void setRegistered(long registered) {
this.registered = registered;
}
public long getLastSeen() {
return lastSeen;
}
public void setLastSeen(long lastSeen) {
this.lastSeen = lastSeen;
}
public void setBanned(boolean banned) {
this.banned = banned;
}
public boolean isBanned() {
return banned;
}
public boolean isOpped() {
return opped;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserInfo userInfo = (UserInfo) o;
return registered == userInfo.registered &&
lastSeen == userInfo.lastSeen &&
banned == userInfo.banned &&
opped == userInfo.opped &&
Objects.equal(uuid, userInfo.uuid) &&
Objects.equal(name, userInfo.name);
}
@Override
public int hashCode() {
return Objects.hashCode(uuid, name, registered, lastSeen, banned, opped);
}
}

View File

@ -1,12 +1,12 @@
package main.java.com.djrapitops.plan.data.cache;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.UserInfo;
/**
* This interface can be extended with anything as the process method and
* given to the Database.
* <p>
* The process method will be called with the UserData object fetched from the
* The process method will be called with the UserInfo object fetched from the
* database.
*
* @author Rsl1122
@ -16,11 +16,11 @@ import main.java.com.djrapitops.plan.data.UserData;
public interface DBCallableProcessor {
/**
* Method used to do multiple things to UserData objects such as Caching,
* Method used to do multiple things to UserInfo objects such as Caching,
* changing properties etc.
*
* @param data UserData object given to the DBCallableProcessor by the
* @param data UserInfo object given to the DBCallableProcessor by the
* method it was given as parameter to.
*/
void process(UserData data);
void process(UserInfo data);
}

View File

@ -3,16 +3,12 @@ package main.java.com.djrapitops.plan.data.cache;
import com.djrapitops.plugin.task.AbsRunnable;
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.utilities.analysis.MathUtils;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
@ -32,7 +28,6 @@ public class DataCache extends SessionCache {
//Cache
private Map<String, Integer> commandUse;
private List<List<TPS>> unsavedTPSHistory;
// Queues
@ -58,7 +53,6 @@ public class DataCache extends SessionCache {
plugin.disablePlugin();
return;
}
unsavedTPSHistory = new ArrayList<>();
startAsyncPeriodicSaveTask();
}
@ -98,7 +92,6 @@ public class DataCache extends SessionCache {
periodicTaskIsSaving = true;
Log.debug("Database", "Periodic Cache Save");
saveCommandUse();
saveUnsavedTPSHistory();
timesSaved++;
} catch (Exception e) {
Log.toLog(this.getClass().getName() + "(" + this.getName() + ")", e);
@ -122,41 +115,6 @@ public class DataCache extends SessionCache {
}
}
public void saveUnsavedTPSHistory() {
List<TPS> averages = calculateAverageTpsForEachMinute();
if (averages.isEmpty()) {
return;
}
try {
Log.debug("Database", "Periodic TPS Save: " + averages.size());
db.getTpsTable().saveTPSData(averages);
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
}
}
private List<TPS> calculateAverageTpsForEachMinute() {
final List<TPS> averages = new ArrayList<>();
if (unsavedTPSHistory.isEmpty()) {
return new ArrayList<>();
}
List<List<TPS>> copy = new ArrayList<>(unsavedTPSHistory);
for (List<TPS> history : copy) {
final long lastDate = history.get(history.size() - 1).getDate();
final double averageTPS = MathUtils.round(MathUtils.averageDouble(history.stream().map(TPS::getTicksPerSecond)));
final int averagePlayersOnline = (int) MathUtils.averageInt(history.stream().map(TPS::getPlayers));
final double averageCPUUsage = MathUtils.round(MathUtils.averageDouble(history.stream().map(TPS::getCPUUsage)));
final long averageUsedMemory = MathUtils.averageLong(history.stream().map(TPS::getUsedMemory));
final int averageEntityCount = (int) MathUtils.averageInt(history.stream().map(TPS::getEntityCount));
final int averageChunksLoaded = (int) MathUtils.averageInt(history.stream().map(TPS::getChunksLoaded));
averages.add(new TPS(lastDate, averageTPS, averagePlayersOnline, averageCPUUsage, averageUsedMemory, averageEntityCount, averageChunksLoaded));
}
unsavedTPSHistory.removeAll(copy);
return averages;
}
/**
* Used to get the cached commandUse.
*
@ -176,9 +134,4 @@ public class DataCache extends SessionCache {
commandUse.put(command, amount + 1);
}
public void addTPSLastMinute(List<TPS> history) {
// Copy the contents to avoid reference, thus making the whole calculation pointless.
unsavedTPSHistory.add(new ArrayList<>(history));
}
}

View File

@ -1,123 +0,0 @@
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.UserData;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.ui.webserver.response.InspectPageResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.api.JsonResponse;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.ExportUtility;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.util.*;
/**
* This class stores UserData objects used for displaying the Html pages.
*
* @author Rsl1122
* @since 2.0.0
*/
@Deprecated
public class InspectCacheHandler {
private final DataCache dataCache;
private final Map<UUID, UserData> cache;
private final Map<UUID, Long> cacheTimes;
/**
* Class constructor.
*
* @param plugin Current instance of Plan.class
*/
public InspectCacheHandler(Plan plugin) {
this.dataCache = plugin.getDataCache();
this.cache = new HashMap<>();
cacheTimes = new HashMap<>();
}
/**
* Caches the UserData object to InspectCache.
* <p>
* If the Userdata is cached in DataCache it will be used. Otherwise the Get
* Queue will handle the DBCallableProcessor.
*
* @param uuid UUID of the player.
*/
@Deprecated // Does not cache anything anymore // TODO Remove
public void cache(UUID uuid) {
DBCallableProcessor cacher = data -> {
UserData userData = new UserData(data);
cache.put(uuid, userData);
cacheTimes.put(uuid, MiscUtils.getTime());
PageCacheHandler.cachePage("inspectPage: " + uuid, () -> new InspectPageResponse(Plan.getInstance().getUiServer().getDataReqHandler(), uuid));
PageCacheHandler.cachePage("inspectionJson: " + uuid, () -> new JsonResponse(userData));
try {
ExportUtility.writeInspectHtml(data, ExportUtility.getPlayersFolder(ExportUtility.getFolder()), HtmlUtils.getStringFromResource("player.html"));
} catch (FileNotFoundException e) {
Log.toLog(this.getClass().getName(), e);
}
};
}
/**
* Used to cache all UserData to the InspectCache from the cache and
* provided database.
*
* @param db Database to cache from if data is not in the cache.
* @throws SQLException If Database is not properly enabled
*/
public void cacheAllUserData(Database db) throws SQLException {
List<UserData> userDataForUUIDS = db.getUserDataForUUIDS(db.getUsersTable().getSavedUUIDs());
long time = MiscUtils.getTime();
for (UserData uData : userDataForUUIDS) {
UUID uuid = uData.getUuid();
cache.put(uuid, new UserData(uData));
cacheTimes.put(uuid, time);
}
}
/**
* Checks the cache for UserData matching UUID.
*
* @param uuid UUID of the Player
* @return UserData that matches the player, null if not cached.
*/
public UserData getFromCache(UUID uuid) {
return cache.get(uuid);
}
/**
* Returns the Epoch millisecond the data was cached to the inspect cache.
*
* @param uuid UUID of the player.
* @return -1 when not cached or Epoch millisecond.
*/
public long getCacheTime(UUID uuid) {
return cacheTimes.getOrDefault(uuid, -1L);
}
/**
* Check if the data of a player is in the inspect cache.
*
* @param uuid UUID of player.
* @return true if cached.
*/
public boolean isCached(UUID uuid) {
return cache.containsKey(uuid);
}
/**
* Used to get all cached userdata objects.
*
* @return List of cached userdata objects.
*/
public List<UserData> getCachedUserData() {
return new ArrayList<>(cache.values());
}
}

View File

@ -0,0 +1,45 @@
/*
* 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;
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.queue.processing.Processor;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import java.sql.SQLException;
import java.util.List;
/**
* //TODO Class Javadoc Comment
*
* @author Rsl1122
*/
public class TPSInsertProcessor extends Processor<List<TPS>> {
public TPSInsertProcessor(List<TPS> object) {
super(object);
}
@Override
public void process() {
List<TPS> history = object;
final long lastDate = history.get(history.size() - 1).getDate();
final double averageTPS = MathUtils.round(MathUtils.averageDouble(history.stream().map(TPS::getTicksPerSecond)));
final int averagePlayersOnline = (int) MathUtils.averageInt(history.stream().map(TPS::getPlayers));
final double averageCPUUsage = MathUtils.round(MathUtils.averageDouble(history.stream().map(TPS::getCPUUsage)));
final long averageUsedMemory = MathUtils.averageLong(history.stream().map(TPS::getUsedMemory));
final int averageEntityCount = (int) MathUtils.averageInt(history.stream().map(TPS::getEntityCount));
final int averageChunksLoaded = (int) MathUtils.averageInt(history.stream().map(TPS::getChunksLoaded));
TPS tps = new TPS(lastDate, averageTPS, averagePlayersOnline, averageCPUUsage, averageUsedMemory, averageEntityCount, averageChunksLoaded);
try {
Plan.getInstance().getDB().getTpsTable().insertTPS(tps);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
}
}

View File

@ -30,7 +30,7 @@ public class IPUpdateProcessor extends PlayerProcessor {
UUID uuid = getUUID();
String country = GeolocationCacheHandler.getCountry(ip);
try {
Plan.getInstance().getDB().getIpsTable().updateIP(uuid, ip, country);
Plan.getInstance().getDB().getIpsTable().saveIP(uuid, ip, country);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}

View File

@ -99,7 +99,7 @@ public class PlanPlayerListener implements Listener {
cache.cacheSession(uuid, Session.start(time, world, gm));
plugin.addToProcessQueue(
new RegisterProcessor(this, uuid, time, playerName, playersOnline),
new RegisterProcessor(this, uuid, player.getFirstPlayed(), playerName, playersOnline),
new IPUpdateProcessor(uuid, ip),
new NameProcessor(uuid, playerName, displayName) // TODO NameCache to DataCache
);

View File

@ -6,6 +6,7 @@ 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.data.cache.DataCache;
import main.java.com.djrapitops.plan.data.handling.TPSInsertProcessor;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import org.bukkit.World;
@ -54,8 +55,7 @@ public class TPSCountTimer extends AbsRunnable {
history.add(tps);
if (history.size() >= 60) {
// TODO Process & Save to DB with a new Processor.
dataCache.addTPSLastMinute(history);
plugin.addToProcessQueue(new TPSInsertProcessor(new ArrayList<>(history)));
history.clear();
}
}

View File

@ -4,6 +4,8 @@
*/
package main.java.com.djrapitops.plan.data.server;
import com.google.common.base.Objects;
import java.util.UUID;
/**
@ -51,4 +53,20 @@ public class ServerInfo {
public void setId(int id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ServerInfo that = (ServerInfo) o;
return id == that.id &&
Objects.equal(uuid, that.uuid) &&
Objects.equal(name, that.name) &&
Objects.equal(webAddress, that.webAddress);
}
@Override
public int hashCode() {
return Objects.hashCode(id, uuid, name, webAddress);
}
}

View File

@ -1,7 +1,7 @@
package main.java.com.djrapitops.plan.database;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.UserInfo;
import main.java.com.djrapitops.plan.database.tables.*;
import org.apache.commons.dbcp2.BasicDataSource;
@ -29,6 +29,11 @@ public abstract class Database {
*/
protected UsersTable usersTable;
/**
* Table representing plan_user_info in the database.
*/
protected UserInfoTable userInfoTable;
/**
* Table representing plan_actions in the database.
*/
@ -120,7 +125,7 @@ public abstract class Database {
}
/**
* Used to get all UserData for multiple UUIDs.
* Used to get all UserInfo for multiple UUIDs.
* <p>
* Should only be called from async thread.
*
@ -128,7 +133,7 @@ public abstract class Database {
* @return Data for matching UUIDs.
* @throws SQLException If database error occurs.
*/
public abstract List<UserData> getUserDataForUUIDS(Collection<UUID> uuids) throws SQLException;
public abstract List<UserInfo> getUserDataForUUIDS(Collection<UUID> uuids) throws SQLException;
/**
* Check if the user is saved in the database.
@ -335,6 +340,9 @@ public abstract class Database {
return actionsTable;
}
public UserInfoTable getUserInfoTable() {
return userInfoTable;
}
public BasicDataSource getDataSource() {
return dataSource;
}

View File

@ -2,7 +2,7 @@ package main.java.com.djrapitops.plan.database.databases;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.UserInfo;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.database.tables.*;
import main.java.com.djrapitops.plan.utilities.Benchmark;
@ -41,6 +41,7 @@ public abstract class SQLDB extends Database {
tpsTable = new TPSTable(this, usingMySQL);
usersTable = new UsersTable(this, usingMySQL);
userInfoTable = new UserInfoTable(this, usingMySQL);
actionsTable = new ActionsTable(this, usingMySQL);
ipsTable = new IPsTable(this, usingMySQL);
nicknamesTable = new NicknamesTable(this, usingMySQL);
@ -151,7 +152,7 @@ public abstract class SQLDB extends Database {
*/
public Table[] getAllTables() {
return new Table[]{
serverTable, usersTable, ipsTable,
serverTable, usersTable, userInfoTable, ipsTable,
nicknamesTable, sessionsTable, killsTable,
commandUseTable, actionsTable, tpsTable,
worldTable, worldTimesTable, securityTable
@ -167,8 +168,9 @@ public abstract class SQLDB extends Database {
return new Table[]{
ipsTable, nicknamesTable, killsTable,
worldTimesTable, sessionsTable, actionsTable,
worldTable, usersTable, commandUseTable,
tpsTable, serverTable
worldTable, userInfoTable, usersTable,
commandUseTable, tpsTable, securityTable,
serverTable
};
}
@ -295,7 +297,7 @@ public abstract class SQLDB extends Database {
@Override
public List<UserData> getUserDataForUUIDS(Collection<UUID> uuidsCol) throws SQLException {
public List<UserInfo> getUserDataForUUIDS(Collection<UUID> uuidsCol) throws SQLException {
if (uuidsCol == null || uuidsCol.isEmpty()) {
return new ArrayList<>();
}

View File

@ -39,8 +39,11 @@ public class ActionsTable extends UserIDTable {
private final String columnActionID = "action_id";
private final String columnAdditionalInfo = "additional_info";
private ServerTable serverTable;
public ActionsTable(SQLDB db, boolean usingMySQL) {
super("plan_actions", db, usingMySQL);
serverTable = db.getServerTable();
}
@Override
@ -60,7 +63,6 @@ public class ActionsTable extends UserIDTable {
public void insertAction(UUID uuid, Action action) throws SQLException {
PreparedStatement statement = null;
try {
ServerTable serverTable = db.getServerTable();
statement = prepareStatement("INSERT INTO " + tableName + " ("
+ columnUserID + ", "
+ columnServerID + ", "
@ -96,10 +98,10 @@ public class ActionsTable extends UserIDTable {
PreparedStatement statement = null;
ResultSet set = null;
try {
ServerTable serverTable = db.getServerTable();
statement = prepareStatement(Select.from(tableName, "*")
.where(columnUserID + "=" + usersTable.statementSelectID)
.toString());
statement.setString(1, uuid.toString());
set = statement.executeQuery();
while (set.next()) {
int serverID = set.getInt(columnServerID);

View File

@ -80,7 +80,7 @@ public class IPsTable extends UserIDTable {
}
}
public void updateIP(UUID uuid, String ip, String geolocation) throws SQLException {
public void saveIP(UUID uuid, String ip, String geolocation) throws SQLException {
List<String> ips = getIps(uuid);
if (ips.contains(ip)) {
return;

View File

@ -125,8 +125,8 @@ public class KillsTable extends UserIDTable {
columnWeapon + ", " +
usersUUIDColumn +
" FROM " + tableName +
" WHERE " + columnKillerUserID + "=" + usersTable.statementSelectID +
" JOIN " + usersTable + " on " + usersIDColumn + "=" + columnVictimUserID); // Might not work TODO TEST
" JOIN " + usersTable + " on " + usersIDColumn + "=" + columnVictimUserID +
" WHERE " + columnKillerUserID + "=" + usersTable.statementSelectID);
statement.setString(1, uuid.toString());
set = statement.executeQuery();
while (set.next()) {

View File

@ -184,7 +184,7 @@ public class ServerTable extends Table {
ResultSet set = null;
try {
statement = prepareStatement(Select.from(tableName,
columnServerName)
columnServerID, columnServerName)
.toString());
set = statement.executeQuery();
while (set.next()) {

View File

@ -172,10 +172,15 @@ public class SessionsTable extends UserIDTable {
long end = set.getLong(columnSessionEnd);
String serverName = serverNames.get(set.getInt(columnServerID));
if (serverName == null) {
throw new IllegalStateException("Server not present");
}
int deaths = set.getInt(columnDeaths);
int mobKills = set.getInt(columnMobKills);
List<Session> sessions = sessionsByServer.getOrDefault(serverName, new ArrayList<>());
sessions.add(new Session(id, start, end, deaths, mobKills));
sessionsByServer.put(serverName, sessions);
}
return sessionsByServer;
} finally {
@ -204,6 +209,18 @@ public class SessionsTable extends UserIDTable {
return getPlaytime(uuid, Plan.getServerUUID());
}
/**
* Get Playtime of a Player after Epoch ms on THIS server.
*
* @param uuid UUID of the player.
* @param afterDate Epoch ms (Playtime after this date is calculated)
* @return Milliseconds played on THIS server. 0 if player or server not found.
* @throws SQLException
*/
public long getPlaytime(UUID uuid, long afterDate) throws SQLException {
return getPlaytime(uuid, Plan.getServerUUID(), afterDate);
}
/**
* Get Total Playtime of a Player on a server.
*
@ -385,9 +402,9 @@ public class SessionsTable extends UserIDTable {
ResultSet set = null;
try {
statement = prepareStatement("SELECT" +
" (COUNT(" + columnID + ") - SUM(" + columnSessionStart + ")) as logintimes" +
" COUNT(*) as logintimes" +
" FROM " + tableName +
" WHERE " + columnSessionStart + ">?" +
" WHERE (" + columnSessionStart + " >= ?)" +
" AND " + columnUserID + "=" + usersTable.statementSelectID +
" AND " + columnServerID + "=" + serverTable.statementSelectServerID);
statement.setLong(1, afterDate);

View File

@ -1,9 +1,8 @@
package main.java.com.djrapitops.plan.database.tables;
import com.djrapitops.plugin.api.TimeAmount;
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.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;
@ -25,7 +24,7 @@ import java.util.List;
*/
public class TPSTable extends Table {
private final String columnServerID = "server_id"; //TODO
private final String columnServerID = "server_id";
private final String columnDate = "date";
private final String columnTPS = "tps";
private final String columnPlayers = "players_online";
@ -34,17 +33,21 @@ public class TPSTable extends Table {
private final String columnEntities = "entities";
private final String columnChunksLoaded = "chunks_loaded";
private final ServerTable serverTable;
/**
* @param db
* @param usingMySQL
*/
public TPSTable(SQLDB db, boolean usingMySQL) {
super("plan_tps", db, usingMySQL);
serverTable = db.getServerTable();
}
@Override
public boolean createTable() {
return createTable(TableSqlParser.createTable(tableName)
.column(columnServerID, Sql.INT).notNull()
.column(columnDate, Sql.LONG).notNull()
.column(columnTPS, Sql.DOUBLE).notNull()
.column(columnPlayers, Sql.INT).notNull()
@ -52,6 +55,7 @@ public class TPSTable extends Table {
.column(columnRAMUsage, Sql.LONG).notNull()
.column(columnEntities, Sql.INT).notNull()
.column(columnChunksLoaded, Sql.INT).notNull()
.foreignKey(columnServerID, serverTable.getTableName(), serverTable.getColumnID())
.toString()
);
}
@ -65,7 +69,11 @@ public class TPSTable extends Table {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement(Select.all(tableName).toString());
statement = prepareStatement(Select.all(tableName)
.where(columnServerID + "=" + serverTable.statementSelectServerID)
.toString());
statement.setFetchSize(5000);
statement.setString(1, Plan.getServerUUID().toString());
set = statement.executeQuery();
while (set.next()) {
long date = set.getLong(columnDate);
@ -85,30 +93,11 @@ public class TPSTable extends Table {
}
}
/**
* @param data
* @throws SQLException
*/
public void saveTPSData(List<TPS> data) throws SQLException {
List<List<TPS>> batches = DBUtils.splitIntoBatches(data);
batches.forEach(batch -> {
try {
saveTPSBatch(batch);
} catch (SQLException e) {
Log.toLog("UsersTable.saveUserDataInformationBatch", e);
}
});
db.setAvailable();
}
private void saveTPSBatch(List<TPS> batch) throws SQLException {
if (batch.isEmpty()) {
return;
}
public void insertTPS(TPS tps) throws SQLException {
PreparedStatement statement = null;
try {
statement = prepareStatement("INSERT INTO " + tableName + " ("
+ columnServerID + ", "
+ columnDate + ", "
+ columnTPS + ", "
+ columnPlayers + ", "
@ -116,21 +105,19 @@ public class TPSTable extends Table {
+ columnRAMUsage + ", "
+ columnEntities + ", "
+ columnChunksLoaded
+ ") VALUES (?, ?, ?, ?, ?, ?, ?)");
+ ") VALUES ("
+ serverTable.statementSelectServerID + ", "
+ "?, ?, ?, ?, ?, ?, ?)");
for (TPS tps : batch) {
statement.setLong(1, tps.getDate());
statement.setDouble(2, tps.getTicksPerSecond());
statement.setInt(3, tps.getPlayers());
statement.setDouble(4, tps.getCPUUsage());
statement.setLong(5, tps.getUsedMemory());
statement.setDouble(6, tps.getEntityCount());
statement.setDouble(7, tps.getChunksLoaded());
statement.addBatch();
}
statement.executeBatch();
commit(statement.getConnection());
statement.setString(1, Plan.getServerUUID().toString());
statement.setLong(2, tps.getDate());
statement.setDouble(3, tps.getTicksPerSecond());
statement.setInt(4, tps.getPlayers());
statement.setDouble(5, tps.getCPUUsage());
statement.setLong(6, tps.getUsedMemory());
statement.setDouble(7, tps.getEntityCount());
statement.setDouble(8, tps.getChunksLoaded());
statement.execute();
} finally {
close(statement);
}
@ -143,8 +130,8 @@ public class TPSTable extends Table {
PreparedStatement statement = null;
try {
statement = prepareStatement("DELETE FROM " + tableName + " WHERE (" + columnDate + "<?)");
// More than 5 Weeks ago.
long fiveWeeks = TimeAmount.WEEK.ms() * 5L;
// More than 2 Months ago.
long fiveWeeks = TimeAmount.MONTH.ms() * 2L;
statement.setLong(1, MiscUtils.getTime() - fiveWeeks);
statement.execute();
} finally {

View File

@ -115,6 +115,7 @@ public abstract class Table {
* @throws SQLException
*/
protected PreparedStatement prepareStatement(String sql) throws SQLException {
System.out.println(sql);
return getConnection().prepareStatement(sql);
}

View File

@ -23,27 +23,6 @@ public abstract class UserIDTable extends Table {
usersTable = db.getUsersTable();
}
@Deprecated
protected boolean removeDataOf(int userID) {
PreparedStatement statement = null;
try {
statement = prepareStatement("DELETE FROM " + tableName + " WHERE (" + columnUserID + "=?)");
statement.setInt(1, userID);
statement.execute();
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);
}
}
public boolean removeUser(UUID uuid) {
PreparedStatement statement = null;
try {

View File

@ -4,9 +4,20 @@
*/
package main.java.com.djrapitops.plan.database.tables;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserInfo;
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.database.sql.Update;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* //TODO Class Javadoc Comment
@ -16,7 +27,6 @@ import main.java.com.djrapitops.plan.database.sql.TableSqlParser;
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";
@ -41,4 +51,138 @@ public class UserInfoTable extends UserIDTable {
.foreignKey(columnServerID, serverTable.getTableName(), serverTable.getColumnID())
.toString());
}
public void registerUserInfo(UUID uuid, long registered) throws SQLException {
if (!usersTable.isRegistered(uuid)) {
usersTable.registerUser(uuid, registered, "Waiting for Update..");
}
PreparedStatement statement = null;
try {
statement = prepareStatement("INSERT INTO " + tableName + " (" +
columnUserID + ", " +
columnRegistered + ", " +
columnServerID +
") VALUES (" +
usersTable.statementSelectID + ", " +
"?, " +
serverTable.statementSelectServerID + ")");
statement.setString(1, uuid.toString());
statement.setLong(2, registered);
statement.setString(3, Plan.getServerUUID().toString());
statement.execute();
} finally {
close(statement);
}
}
public boolean isRegistered(UUID uuid) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement(Select.from(tableName, columnUserID)
.where(columnUserID + "=" + usersTable.statementSelectID)
.toString());
statement.setString(1, uuid.toString());
set = statement.executeQuery();
return set.next();
} finally {
close(set, statement);
}
}
public void updateOpAndBanStatus(UUID uuid, boolean opped, boolean banned) throws SQLException {
PreparedStatement statement = null;
try {
statement = prepareStatement(Update.values(tableName, columnOP, columnBanned)
.where(columnUserID + "=" + usersTable.statementSelectID)
.toString());
statement.setBoolean(1, opped);
statement.setBoolean(2, banned);
statement.setString(3, uuid.toString());
statement.execute();
} finally {
close(statement);
}
}
public UserInfo getUserInfo(UUID uuid) throws SQLException {
return getUserInfo(uuid, Plan.getServerUUID());
}
public UserInfo getUserInfo(UUID uuid, UUID serverUUID) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
String usersIDColumn = usersTable + "." + usersTable.getColumnID();
String usersNameColumn = usersTable + "." + usersTable.getColumnName() + " as name";
statement = prepareStatement("SELECT " +
tableName + "." + columnRegistered + ", " +
columnOP + ", " +
columnBanned + ", " +
usersNameColumn +
" FROM " + tableName +
" JOIN " + usersTable + " on " + usersIDColumn + "=" + columnUserID +
" WHERE " + columnUserID + "=" + usersTable.statementSelectID +
" AND " + columnServerID + "=" + serverTable.statementSelectServerID
);
statement.setString(1, uuid.toString());
statement.setString(2, serverUUID.toString());
set = statement.executeQuery();
if (set.next()) {
long registered = set.getLong(columnRegistered);
boolean opped = set.getBoolean(columnOP);
boolean banned = set.getBoolean(columnBanned);
String name = set.getString("name");
return new UserInfo(uuid, name, registered, opped, banned);
}
return null;
} finally {
close(set, statement);
}
}
/**
* Used for getting info of all users on THIS server.
*
* @return List of UserInfo objects.
*/
public List<UserInfo> getAllUserInfo() throws SQLException {
return getAllUserInfo(Plan.getServerUUID());
}
public List<UserInfo> getAllUserInfo(UUID serverUUID) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
List<UserInfo> userInfo = new ArrayList<>();
String usersIDColumn = usersTable + "." + usersTable.getColumnID();
String usersUUIDColumn = usersTable + "." + usersTable.getColumnUUID() + " as uuid";
String usersNameColumn = usersTable + "." + usersTable.getColumnName() + " as name";
statement = prepareStatement("SELECT " +
tableName + "." + columnRegistered + ", " +
columnOP + ", " +
columnBanned + ", " +
usersNameColumn + ", " +
usersUUIDColumn +
" FROM " + tableName +
" JOIN " + usersTable + " on " + usersIDColumn + "=" + columnUserID +
" WHERE " + columnServerID + "=" + serverTable.statementSelectServerID
);
statement.setFetchSize(2000);
statement.setString(1, serverUUID.toString());
set = statement.executeQuery();
while (set.next()) {
long registered = set.getLong(columnRegistered);
boolean opped = set.getBoolean(columnOP);
boolean banned = set.getBoolean(columnBanned);
String name = set.getString("name");
UUID uuid = UUID.fromString(set.getString("uuid"));
userInfo.add(new UserInfo(uuid, name, registered, opped, banned));
}
return userInfo;
} finally {
close(set, statement);
}
}
}

View File

@ -227,15 +227,36 @@ public class UsersTable extends UserIDTable {
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 = prepareStatement("UPDATE " + tableName + " SET "
+ columnTimesKicked + "=" + columnTimesKicked + "+ 1" +
" WHERE " + columnUUID + "=?");
statement.setString(1, uuid.toString());
statement.execute();
} finally {
endTransaction(statement);
close(statement);
}
}
public String getPlayerName(UUID uuid) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement(Select.from(tableName, columnName)
.where(columnUUID + "=?")
.toString());
statement.setString(1, uuid.toString());
set = statement.executeQuery();
if (set.next()) {
return set.getString(columnName);
}
return null;
} finally {
close(set, statement);
}
}
public String getColumnName() {
return columnName;
}
}

View File

@ -118,8 +118,8 @@ public class WorldTimesTable extends UserIDTable {
columnSpectator + ", " +
worldNameColumn +
" FROM " + tableName +
" WHERE " + columnUserID + "=" + usersTable.statementSelectID +
" JOIN " + worldTable + " on " + worldIDColumn + "=" + columnWorldId // TODO TEST
" JOIN " + worldTable + " on " + worldIDColumn + "=" + columnWorldId +
" WHERE " + columnUserID + "=" + usersTable.statementSelectID
);
statement.setString(1, uuid.toString());
set = statement.executeQuery();

View File

@ -1,13 +1,7 @@
package main.java.com.djrapitops.plan.ui.html;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.cache.AnalysisCacheHandler;
import main.java.com.djrapitops.plan.data.cache.InspectCacheHandler;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.PlaceholderUtils;
import java.io.FileNotFoundException;
import java.util.UUID;
/**
@ -16,17 +10,13 @@ import java.util.UUID;
@Deprecated //TODO Make an utility class for parsing files to give to the page cache.
public class DataRequestHandler {
private final InspectCacheHandler inspectCache;
private final AnalysisCacheHandler analysisCache;
/**
* Class Constructor.
*
* @param plugin Current instance of Plan
*/
@Deprecated
public DataRequestHandler(Plan plugin) {
this.inspectCache = plugin.getInspectCache();
this.analysisCache = plugin.getAnalysisCache();
}
/**
@ -35,31 +25,23 @@ public class DataRequestHandler {
* @param uuid UUID of Player
* @return true if cached.
*/
@Deprecated
public boolean checkIfCached(UUID uuid) {
return inspectCache.isCached(uuid);
// TODO Check from PageCache
return false;
}
/**
* Returns the player.html as string with replaced placeholders.
*
* @param uuid UUID of player, whose UserData is used to replace
* @param uuid UUID of player, whose UserInfo is used to replace
* placeholders with
* @return The html
*/
@Deprecated
public String getInspectHtml(UUID uuid) {
try {
UserData data = inspectCache.getFromCache(uuid);
if (data == null) {
return "<h1>404 Data was not found in cache</h1>";
}
return HtmlUtils.replacePlaceholders(
HtmlUtils.getStringFromResource("player.html"),
PlaceholderUtils.getInspectReplaceRules(data)
);
} catch (FileNotFoundException ex) {
return "<h1>404 player.html was not found. </h1>";
}
// TODO Get from PageCache
return "";
}
/**
@ -67,17 +49,10 @@ public class DataRequestHandler {
*
* @return the html
*/
@Deprecated
public String getServerHtml() {
try {
if (!analysisCache.isCached()) {
return "<h1>404 Data was not found in cache</h1>";
}
return HtmlUtils.replacePlaceholders(
HtmlUtils.getStringFromResource("server.html"),
PlaceholderUtils.getAnalysisReplaceRules(analysisCache.getData()));
} catch (FileNotFoundException ex) {
return "<h1>404 server.html was not found</h1>";
}
// TODO Get from PageCache
return "";
}
/**
@ -85,7 +60,9 @@ public class DataRequestHandler {
*
* @return true if cached.
*/
@Deprecated
public boolean checkIfAnalysisIsCached() {
return analysisCache.isCached();
// TODO Check from PageCache
return false;
}
}

View File

@ -1,17 +1,14 @@
package main.java.com.djrapitops.plan.ui.html.tables;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.utilities.FormatUtils;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.data.UserInfo;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.AnalysisUtils;
import java.util.List;
/**
* @author Rsl1122
*/
// TODO Rewrite!
public class PlayersTableCreator {
/**
@ -22,36 +19,36 @@ public class PlayersTableCreator {
}
/**
* @param data The list of the {@link UserData} Objects from which the players table should be created
* @param data The list of the {@link UserInfo} Objects from which the players table should be created
* @return The created players table
*/
public static String createSortablePlayersTable(List<UserData> data) {
public static String createSortablePlayersTable(List<UserInfo> data) {
StringBuilder html = new StringBuilder();
long now = MiscUtils.getTime();
int i = 0;
for (UserData uData : data) {
for (UserInfo uData : data) {
if (i >= 750) {
break;
}
try {
boolean isBanned = uData.isBanned();
boolean isUnknown = uData.getLoginTimes() == 1;
boolean isActive = AnalysisUtils.isActive(now, uData.getLastPlayed(), uData.getPlayTime(), uData.getLoginTimes());
String activityString = getActivityString(isBanned, isUnknown, isActive);
html.append(Html.TABLELINE_PLAYERS.parse(
Html.LINK.parse(HtmlUtils.getRelativeInspectUrl(uData.getName()), uData.getName()),
activityString,
String.valueOf(uData.getPlayTime()), FormatUtils.formatTimeAmount(uData.getPlayTime()),
String.valueOf(uData.getLoginTimes()),
String.valueOf(uData.getRegistered()), FormatUtils.formatTimeStampYear(uData.getRegistered()),
String.valueOf(uData.getLastPlayed()), FormatUtils.formatTimeStamp(uData.getLastPlayed()),
String.valueOf(uData.getGeolocations()) //TODO get last Geoloc
));
// boolean isBanned = uData.isBanned();
// boolean isUnknown = uData.getLoginTimes() == 1;
// boolean isActive = AnalysisUtils.isActive(now, uData.getLastPlayed(), uData.getPlayTime(), uData.getLoginTimes());
//
// String activityString = getActivityString(isBanned, isUnknown, isActive);
//
// html.append(Html.TABLELINE_PLAYERS.parse(
// Html.LINK.parse(HtmlUtils.getRelativeInspectUrl(uData.getName()), uData.getName()),
// activityString,
// String.valueOf(uData.getPlayTime()), FormatUtils.formatTimeAmount(uData.getPlayTime()),
// String.valueOf(uData.getLoginTimes()),
// String.valueOf(uData.getRegistered()), FormatUtils.formatTimeStampYear(uData.getRegistered()),
// String.valueOf(uData.getLastPlayed()), FormatUtils.formatTimeStamp(uData.getLastPlayed()),
// String.valueOf(uData.getGeolocations()) //TODO get last Geoloc
// ));
} catch (NullPointerException ignored) {
}

View File

@ -18,7 +18,7 @@ import java.util.Map;
public class AnalyzeWebAPI implements WebAPI {
@Override
public Response onResponse(Plan plan, Map<String, String> variables) {
plan.getAnalysisCache().updateCache();
// TODO plan.getAnalysisCache().updateCache();
return PageCacheHandler.loadPage("success", SuccessResponse::new);
}
}

View File

@ -35,7 +35,7 @@ public class InspectWebAPI implements WebAPI {
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
plan.getInspectCache().cache(uuid);
// TODO plan.getInspectCache().cache(uuid);
return PageCacheHandler.loadPage("success", SuccessResponse::new);
}

View File

@ -5,44 +5,41 @@
package main.java.com.djrapitops.plan.ui.webserver.api.bukkit;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.cache.PageCacheHandler;
import main.java.com.djrapitops.plan.ui.webserver.response.Response;
import main.java.com.djrapitops.plan.ui.webserver.response.api.BadRequestResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.api.JsonResponse;
import main.java.com.djrapitops.plan.utilities.uuid.UUIDUtility;
import main.java.com.djrapitops.plan.utilities.webserver.api.WebAPI;
import java.util.Map;
import java.util.UUID;
/**
* @author Fuzzlemann
*/
@Deprecated // UserData objects should not be sent between servers.
public class InspectionWebAPI implements WebAPI {
@Override
public Response onResponse(Plan plan, Map<String, String> variables) {
String playerString = variables.get("player");
if (playerString == null) {
String error = "Player String not included";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
UUID uuid = UUIDUtility.getUUIDOf(playerString);
if (uuid == null) {
String error = "UUID not found";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
UserData userData = plan.getInspectCache().getFromCache(uuid);
if (userData == null) {
String error = "User not cached";
return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
}
return PageCacheHandler.loadPage("inspectionJson: " + uuid, () -> new JsonResponse(plan.getInspectCache().getFromCache(uuid)));
// String playerString = variables.get("player");
//
// if (playerString == null) {
// String error = "Player String not included";
// return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
// }
//
// UUID uuid = UUIDUtility.getUUIDOf(playerString);
//
// if (uuid == null) {
// String error = "UUID not found";
// return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
// }
//
// UserInfo userInfo = plan.getInspectCache().getFromCache(uuid);
//
// if (userInfo == null) {
// String error = "User not cached";
// return PageCacheHandler.loadPage(error, () -> new BadRequestResponse(error));
// }
//
// return PageCacheHandler.loadPage("inspectionJson: " + uuid, () -> new JsonResponse(plan.getInspectCache().getFromCache(uuid)));
return new BadRequestResponse("Not implemented");
}
}

View File

@ -1,7 +1,7 @@
package main.java.com.djrapitops.plan.ui.webserver.response;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.UserInfo;
import main.java.com.djrapitops.plan.ui.html.Html;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.comparators.UserDataNameComparator;
@ -16,10 +16,10 @@ public class PlayersPageResponse extends Response {
public PlayersPageResponse(Plan plugin) {
super.setHeader("HTTP/1.1 200 OK");
super.setContent(buildContent(plugin.getInspectCache().getCachedUserData()));
// super.setContent(buildContent(plugin.getInspectCache().getCachedUserData()));
}
public static String buildContent(List<UserData> cached) {
public static String buildContent(List<UserInfo> cached) {
StringBuilder html = new StringBuilder("<!DOCTYPE html><html><body><h1>Cached Players</h1><p>");
int size = cached.size();
@ -29,8 +29,8 @@ public class PlayersPageResponse extends Response {
cached.sort(new UserDataNameComparator());
int i = 1;
for (UserData userData : cached) {
String name = userData.getName();
for (UserInfo userInfo : cached) {
String name = userInfo.getName();
String link = Html.LINK.parse(HtmlUtils.getRelativeInspectUrl(name), name);
html.append("<td>").append(link).append("</td>");

View File

@ -68,10 +68,10 @@ public class ManageUtils {
public static boolean clearAndCopy(Database clearAndCopyToDB, Database copyFromDB) {
try {
clearAndCopyToDB.removeAllData();
//TODO List<UserData> allUserData = copyFromDB.getUserDataForUUIDS(copyFromDB.getSavedUUIDs());
// clearAndCopyToDB.saveMultipleUserData(allUserData);
//TODO List<UserInfo> allUserData = copyFromDB.getUserDataForUUIDS(copyFromDB.getSavedUUIDs());
// clearAndCopyToDB.saveMultipleUserData(allUserData);
clearAndCopyToDB.getCommandUseTable().saveCommandUse(copyFromDB.getCommandUseTable().getCommandUse());
clearAndCopyToDB.getTpsTable().saveTPSData(copyFromDB.getTpsTable().getTPSData());
//TODO clearAndCopyToDB.getTpsTable().saveTPSData(copyFromDB.getTpsTable().getTPSData());
} catch (SQLException | NullPointerException e) {
Log.toLog("ManageUtils.move", e);
return false;

View File

@ -3,17 +3,14 @@ package main.java.com.djrapitops.plan.utilities;
import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.command.CommandUtils;
import com.djrapitops.plugin.command.ISender;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
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 java.io.Closeable;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
@ -91,15 +88,11 @@ public class MiscUtils {
final String searchFor = search.toLowerCase();
Database db = Plan.getInstance().getDB();
List<String> matches = new ArrayList<>();
try {
List<UserData> data = db.getUserDataForUUIDS(db.getSavedUUIDs());
matches = data.stream()
.map(UserData::getName)
.filter(name -> name.toLowerCase().contains(searchFor))
.collect(Collectors.toList());
} catch (SQLException e) {
Log.toLog("MiscUtils.getMatchingPlayerNames", e);
}
// try {
// TODO GetMatchingPlayerNamesFromDB
// } catch (SQLException e) {
// Log.toLog("MiscUtils.getMatchingPlayerNames", e);
// }
Collections.sort(matches);
return matches;
}

View File

@ -3,7 +3,7 @@ package main.java.com.djrapitops.plan.utilities;
import com.djrapitops.plugin.utilities.player.Gamemode;
import com.djrapitops.plugin.utilities.player.IOfflinePlayer;
import com.djrapitops.plugin.utilities.player.IPlayer;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.UserInfo;
/**
* @author Rsl1122
@ -20,33 +20,33 @@ public class NewPlayerCreator {
}
/**
* Creates a new instance of UserData with default values.
* Creates a new instance of UserInfo with default values.
*
* @param player Player the UserData is created for.
* @return a new UserData object
* @param player Player the UserInfo is created for.
* @return a new UserInfo object
*/
public static UserData createNewPlayer(IPlayer player) {
public static UserInfo createNewPlayer(IPlayer player) {
return createNewPlayer(player, player.getGamemode());
}
/**
* Creates a new instance of UserData with default values.
* Creates a new instance of UserInfo with default values.
*
* @param player OfflinePlayer the UserData is created for.
* @return a new UserData object
* @param player OfflinePlayer the UserInfo is created for.
* @return a new UserInfo object
*/
public static UserData createNewOfflinePlayer(IOfflinePlayer player) {
public static UserInfo createNewOfflinePlayer(IOfflinePlayer player) {
return createNewPlayer(player, Gamemode.SURVIVAL);
}
/**
* Creates a new instance of UserData with default values.
* Creates a new instance of UserInfo with default values.
*
* @param player Player the UserData is created for.
* @param player Player the UserInfo is created for.
* @param gm Gamemode set as the starting Gamemode
* @return a new UserData object
* @return a new UserInfo object
*/
public static UserData createNewPlayer(IOfflinePlayer player, Gamemode gm) {
public static UserInfo createNewPlayer(IOfflinePlayer player, Gamemode gm) {
return null;
}

View File

@ -3,12 +3,12 @@ package main.java.com.djrapitops.plan.utilities;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.AnalysisData;
import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.ui.html.graphs.PunchCardGraphCreator;
import main.java.com.djrapitops.plan.data.UserInfo;
import java.io.Serializable;
import java.util.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @author Rsl1122
@ -47,10 +47,10 @@ public class PlaceholderUtils {
/**
* Gets the Map that is used to replace placeholders.
*
* @param data UserData used to replace the placeholders with
* @param data UserInfo used to replace the placeholders with
* @return HashMap that contains string for each placeholder.
*/
public static Map<String, Serializable> getInspectReplaceRules(UserData data) {
public static Map<String, Serializable> getInspectReplaceRules(UserInfo data) {
HashMap<String, Serializable> replaceMap = new HashMap<>();
UUID uuid = data.getUuid();
@ -64,18 +64,18 @@ public class PlaceholderUtils {
replaceMap.put("geolocations", "TODO"); //TODO Geolocation list creator &#x2022; name<br>
replaceMap.put("registered", FormatUtils.formatTimeStampYear(data.getRegistered()));
replaceMap.put("lastSeen", FormatUtils.formatTimeStampYear(data.getLastPlayed()));
// replaceMap.put("lastSeen", FormatUtils.formatTimeStampYear(data.getLastPlayed()));
replaceMap.put("sessionCount", data.getSessions().size());
// replaceMap.put("sessionCount", data.getSessions().size());
//TODO replaceMap.put("playtimeTotal", FormatUtils.formatTimeAmount(data.getPlayTime()));
replaceMap.put("kickCount", data.getTimesKicked());
// replaceMap.put("kickCount", data.getTimesKicked());
// replaceMap.put("playerKillCount", data.getPlayerKills().size()); //TODO
// replaceMap.put("mobKillCount", data.getMobKills());
// replaceMap.put("deathCount", data.getDeaths());
Set<Session> sessions = new HashSet<>(data.getSessions());
replaceMap.put("punchCardSeries", PunchCardGraphCreator.createDataSeries(sessions));
// Set<Session> sessions = new HashSet<>(data.getSessions());
// replaceMap.put("punchCardSeries", PunchCardGraphCreator.createDataSeries(sessions));
//TODO WorldTimes worldTimes = data.getWorldTimes();
// TODO replaceMap.put("worldSeries", WorldPieCreator.createSeriesData(worldTimes.getTimes()));
// replaceMap.put("worldTotal", FormatUtils.formatTimeAmount(worldTimes.getTotal()));

View File

@ -5,28 +5,23 @@ 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.data.AnalysisData;
import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.additional.AnalysisType;
import main.java.com.djrapitops.plan.data.additional.HookHandler;
import main.java.com.djrapitops.plan.data.additional.PluginData;
import main.java.com.djrapitops.plan.data.analysis.*;
import main.java.com.djrapitops.plan.data.cache.AnalysisCacheHandler;
import main.java.com.djrapitops.plan.data.cache.DataCache;
import main.java.com.djrapitops.plan.data.cache.InspectCacheHandler;
import main.java.com.djrapitops.plan.data.cache.PageCacheHandler;
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.ui.html.tables.PlayersTableCreator;
import main.java.com.djrapitops.plan.ui.webserver.response.AnalysisPageResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.PlayersPageResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.api.JsonResponse;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.comparators.UserDataLastPlayedComparator;
import java.io.Serializable;
import java.util.*;
@ -38,7 +33,6 @@ import java.util.stream.Collectors;
public class Analysis {
private final Plan plugin;
private final InspectCacheHandler inspectCache;
private int taskId = -1;
/**
@ -48,7 +42,6 @@ public class Analysis {
*/
public Analysis(Plan plugin) {
this.plugin = plugin;
this.inspectCache = plugin.getInspectCache();
}
/**
@ -56,7 +49,7 @@ public class Analysis {
* <p>
* First retrieves all offline players and checks those that are in the
* database. Then runs a new Analysis Task asynchronously. Saves AnalysisData
* to the provided Cache. Saves all UserData to InspectCache for 15 minutes.
* to the provided Cache. Saves all UserInfo to InspectCache for 15 minutes.
*
* @param analysisCache Cache that the data is saved to.
*/
@ -92,42 +85,28 @@ public class Analysis {
Benchmark.start("Fetch Phase");
Log.debug("Database", "Analysis Fetch");
Log.debug("Analysis", "Analysis Fetch Phase");
try {
inspectCache.cacheAllUserData(db);
} catch (Exception ex) {
Log.toLog(this.getClass().getName(), ex);
Log.error(Locale.get(Msg.ANALYSIS_FAIL_FETCH_EXCEPTION).toString());
}
List<UserData> rawData = inspectCache.getCachedUserData();
if (rawData.isEmpty()) {
Log.info(Locale.get(Msg.ANALYSIS_FAIL_NO_DATA).toString());
return false;
}
//TODO Rewrite FETCH
List<TPS> tpsData = new ArrayList<>();
try {
tpsData = db.getTpsTable().getTPSData();
Log.debug("Analysis", "Raw Data Size: " + rawData.size());
Log.debug("Analysis", "TPS Data Size: " + tpsData.size());
} catch (Exception ex) {
Log.toLog(this.getClass().getName(), ex);
}
return analyzeData(rawData, tpsData, analysisCache);
return analyzeData(tpsData, analysisCache);
}
/**
* @param rawData
* @param tpsData
* @param analysisCache
* @return
*/
public boolean analyzeData(List<UserData> rawData, List<TPS> tpsData, AnalysisCacheHandler analysisCache) {
public boolean analyzeData(List<TPS> tpsData, AnalysisCacheHandler analysisCache) {
try {
rawData.sort(new UserDataLastPlayedComparator());
List<UUID> uuids = rawData.stream().map(UserData::getUuid).collect(Collectors.toList());
// rawData.sort(new UserDataLastPlayedComparator());
// List<UUID> uuids = rawData.stream().map(UserInfo::getUuid).collect(Collectors.toList());
Benchmark.start("Create Empty dataset");
DataCache dataCache = plugin.getDataCache();
Map<String, Integer> commandUse = dataCache.getCommandUse();
@ -136,28 +115,33 @@ public class Analysis {
analysisData.setPluginsTabLayout(plugin.getHookHandler().getPluginsTabLayoutForAnalysis());
analysisData.setPlanVersion(plugin.getVersion());
ActivityPart activityPart = analysisData.getActivityPart();
activityPart.setRecentPlayersUUIDs(uuids);
analysisData.getPlayerCountPart().addPlayers(uuids);
activityPart.setRecentPlayers(rawData.stream().map(UserData::getName).collect(Collectors.toList()));
// TODO GetRecentPlayers
// activityPart.setRecentPlayersUUIDs(uuids);
// analysisData.getPlayerCountPart().addPlayers(uuids);
// activityPart.setRecentPlayers(rawData.stream().map(UserInfo::getName).collect(Collectors.toList()));
Benchmark.stop("Analysis", "Create Empty dataset");
long fetchPhaseLength = Benchmark.stop("Analysis", "Fetch Phase");
Benchmark.start("Analysis Phase");
Log.debug("Analysis", "Analysis Phase");
log(Locale.get(Msg.ANALYSIS_PHASE_START).parse(rawData.size(), fetchPhaseLength));
String playersTable = PlayersTableCreator.createSortablePlayersTable(rawData);
analysisData.setPlayersTable(playersTable);
//TODO Fetch Size
log(Locale.get(Msg.ANALYSIS_PHASE_START).parse(0, fetchPhaseLength));
fillDataset(analysisData, rawData);
// TODO Create playersTable
// String playersTable = PlayersTableCreator.createSortablePlayersTable(rawData);
// analysisData.setPlayersTable(playersTable);
fillDataset(analysisData);
// Analyze
analysisData.analyseData();
Benchmark.stop("Analysis", "Analysis Phase");
log(Locale.get(Msg.ANALYSIS_3RD_PARTY).toString());
Log.debug("Analysis", "Analyzing additional data sources (3rd party)");
analysisData.setAdditionalDataReplaceMap(analyzeAdditionalPluginData(uuids));
// TODO analysisData.setAdditionalDataReplaceMap(analyzeAdditionalPluginData(uuids));
analysisCache.cache(analysisData);
long time = Benchmark.stop("Analysis", "Analysis");
@ -171,7 +155,8 @@ public class Analysis {
PageCacheHandler.cachePage("analysisJson", () -> new JsonResponse(analysisData));
PageCacheHandler.cachePage("players", () -> new PlayersPageResponse(plugin));
ExportUtility.export(analysisData, rawData);
// TODO Export
// ExportUtility.export(analysisData, rawData);
} catch (Exception e) {
Log.toLog(this.getClass().getName(), e);
Log.debug("Analysis", "Error: " + e);
@ -187,6 +172,7 @@ public class Analysis {
}
private Map<String, Serializable> analyzeAdditionalPluginData(List<UUID> uuids) {
// TODO Rewrite
Benchmark.start("3rd party");
final Map<String, Serializable> replaceMap = new HashMap<>();
final HookHandler hookHandler = plugin.getHookHandler();
@ -253,7 +239,7 @@ public class Analysis {
taskId = id;
}
private void fillDataset(AnalysisData analysisData, List<UserData> rawData) {
private void fillDataset(AnalysisData analysisData) {
ActivityPart activity = analysisData.getActivityPart();
GamemodePart gmPart = analysisData.getGamemodePart();
GeolocationPart geolocPart = analysisData.getGeolocationPart();
@ -268,46 +254,46 @@ public class Analysis {
Benchmark.start("Fill Dataset");
List<PluginData> banSources = plugin.getHookHandler().getAdditionalDataSources()
.stream().filter(PluginData::isBanData).collect(Collectors.toList());
rawData.forEach(uData -> {
// rawData.forEach(uData -> {
// TODO Map<String, Long> worldTimes = uData.getWorldTimes().getTimes();
// TODO playtime.addToPlaytime(playTime);
joinInfo.addToLoginTimes(uData.getLoginTimes());
joinInfo.addRegistered(uData.getRegistered());
// TODO playtime.addToPlaytime(playTime);
// joinInfo.addToLoginTimes(uData.getLoginTimes());
// joinInfo.addRegistered(uData.getRegistered());
//TODO geolocPart.addGeolocation(uData.getGeolocation());
//TODO geolocPart.addGeolocation(uData.getGeolocation());
final UUID uuid = uData.getUuid();
if (uData.isOp()) {
playerCount.addOP(uuid);
}
// final UUID uuid = uData.getUuid();
// if (uData.isOp()) {
// playerCount.addOP(uuid);
// }
boolean banned = uData.isBanned();
if (!banned) {
banned = banSources.stream()
.anyMatch(banData -> {
Serializable value = banData.getValue(uuid);
if (value instanceof Boolean) {
return (Boolean) value;
}
return false;
});
}
if (banned) {
activity.addBan(uuid);
} else if (uData.getLoginTimes() == 1) {
activity.addJoinedOnce(uuid);
// boolean banned = uData.isBanned();
// if (!banned) {
// banned = banSources.stream()
// .anyMatch(banData -> {
// Serializable value = banData.getValue(uuid);
// if (value instanceof Boolean) {
// return (Boolean) value;
// }
// return false;
// });
// }
//
// if (banned) {
// activity.addBan(uuid);
// } else if (uData.getLoginTimes() == 1) {
// activity.addJoinedOnce(uuid);
// TODO } else if (AnalysisUtils.isActive(now, uData.getLastPlayed(), playTime, uData.getSessionCount())) {
// activity.addActive(uuid);
} else {
activity.addInActive(uuid);
}
// } else {
// activity.addInActive(uuid);
// }
//TODO List<KillData> playerKills = uData.getPlayerKills();
List<Session> sessions = uData.getSessions();
joinInfo.addSessions(uuid, sessions);
});
// List<Session> sessions = uData.getSessions();
// joinInfo.addSessions(uuid, sessions);
// });
Benchmark.stop("Analysis", "Fill Dataset");
}
}

View File

@ -4,7 +4,7 @@ import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.AnalysisData;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.UserInfo;
import main.java.com.djrapitops.plan.ui.webserver.response.PlayersPageResponse;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import main.java.com.djrapitops.plan.utilities.HtmlUtils;
@ -57,7 +57,7 @@ public class ExportUtility {
* @param analysisData
* @param rawData
*/
public static void export(AnalysisData analysisData, List<UserData> rawData) {
public static void export(AnalysisData analysisData, List<UserInfo> rawData) {
if (!Settings.ANALYSIS_EXPORT.isTrue()) {
return;
}
@ -98,15 +98,15 @@ public class ExportUtility {
}
/**
* @param userData
* @param userInfo
* @param playersFolder
*/
public static void writeInspectHtml(UserData userData, File playersFolder, String playerHtml) {
public static void writeInspectHtml(UserInfo userInfo, File playersFolder, String playerHtml) {
if (!Settings.ANALYSIS_EXPORT.isTrue()) {
return;
}
String name = userData.getName();
String name = userInfo.getName();
if (name.endsWith(".")) {
name = name.replace(".", "%2E");
@ -118,7 +118,7 @@ public class ExportUtility {
try {
String inspectHtml = HtmlUtils.replacePlaceholders(playerHtml,
PlaceholderUtils.getInspectReplaceRules(userData));
PlaceholderUtils.getInspectReplaceRules(userInfo));
File playerFolder = new File(playersFolder, name);
playerFolder.mkdirs();
@ -149,7 +149,7 @@ public class ExportUtility {
Files.write(analysisHtmlFile.toPath(), Collections.singletonList(analysisHtml));
}
private static void writePlayersPageHtml(List<UserData> rawData, File playersFolder) throws IOException {
private static void writePlayersPageHtml(List<UserInfo> rawData, File playersFolder) throws IOException {
String playersHtml = PlayersPageResponse.buildContent(rawData);
playersFolder.mkdirs();
File playersHtmlFile = new File(playersFolder, "index.html");

View File

@ -5,17 +5,17 @@
*/
package main.java.com.djrapitops.plan.utilities.comparators;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.UserInfo;
import java.util.Comparator;
/**
* @author Risto
*/
public class UserDataLastPlayedComparator implements Comparator<UserData> {
public class UserDataLastPlayedComparator implements Comparator<UserInfo> {
@Override
public int compare(UserData u1, UserData u2) {
return Long.compare(u2.getLastPlayed(), u1.getLastPlayed());
public int compare(UserInfo u1, UserInfo u2) {
return Long.compare(u2.getLastSeen(), u1.getLastSeen());
}
}

View File

@ -5,17 +5,17 @@
*/
package main.java.com.djrapitops.plan.utilities.comparators;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.UserInfo;
import java.util.Comparator;
/**
* @author Risto
*/
public class UserDataNameComparator implements Comparator<UserData> {
public class UserDataNameComparator implements Comparator<UserInfo> {
@Override
public int compare(UserData u1, UserData u2) {
public int compare(UserInfo u1, UserInfo u2) {
return u1.getName().compareTo(u2.getName());
}
}

View File

@ -1,7 +1,7 @@
package test.java.main.java.com.djrapitops.plan.data;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.UserInfo;
import org.bukkit.plugin.java.JavaPlugin;
import org.junit.Before;
import org.junit.Test;
@ -14,16 +14,16 @@ import org.powermock.modules.junit4.PowerMockRunner;
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(JavaPlugin.class)
public class UserDataTest {
public class UserInfoTest {
// TODO Rewrite
private UserData test;
private UserInfo test;
private Plan plan;
/**
*
*/
public UserDataTest() {
public UserInfoTest() {
}
/**

View File

@ -89,11 +89,12 @@ public class DatabaseCommitTest {
assertFalse(db.getCommandUse().isEmpty());
}
@Ignore("//TODO")
@Test
public void testCommitToDBFile2() throws SQLException {
db.init();
List<TPS> tps = RandomData.randomTPS();
db.getTpsTable().saveTPSData(tps);
// db.getTpsTable().saveTPSData(tps);
db.close();
db.init();
assertFalse(db.getTpsTable().getTPSData().isEmpty());

View File

@ -6,18 +6,20 @@
package test.java.main.java.com.djrapitops.plan.database;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.data.*;
import main.java.com.djrapitops.plan.data.server.ServerInfo;
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.Database;
import main.java.com.djrapitops.plan.database.databases.MySQLDB;
import main.java.com.djrapitops.plan.database.databases.SQLiteDB;
import main.java.com.djrapitops.plan.database.tables.TPSTable;
import main.java.com.djrapitops.plan.database.tables.*;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import main.java.com.djrapitops.plan.utilities.file.FileUtil;
import org.bukkit.plugin.java.JavaPlugin;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
@ -32,8 +34,7 @@ import java.lang.management.OperatingSystemMXBean;
import java.sql.SQLException;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.*;
/**
* @author Rsl1122
@ -46,31 +47,31 @@ public class DatabaseTest {
private Database db;
private Database backup;
private int rows;
private UUID uuid = MockUtils.getPlayerUUID();
private List<String> worlds = Arrays.asList("TestWorld", "TestWorld2");
private UUID uuid2 = MockUtils.getPlayer2UUID();
/**
*
*/
public DatabaseTest() {
}
/**
* @throws IOException
* @throws Exception
*/
@Before
public void setUp() throws Exception {
TestInit t = TestInit.init();
plan = t.getPlanMock();
db = new SQLiteDB(plan, "debug" + MiscUtils.getTime());
db = new SQLiteDB(plan, "debug" + MiscUtils.getTime()) {
@Override
public void startConnectionPingTask() {
}
};
db.init();
db.getServerTable().saveCurrentServerInfo(new ServerInfo(-1, t.getServerUUID(), "ServerName", ""));
File f = new File(plan.getDataFolder(), "Errors.txt");
rows = FileUtil.lines(f).size();
db.init();
}
/**
* @throws IOException
* @throws SQLException
*/
@After
public void tearDown() throws IOException, SQLException {
db.close();
@ -89,123 +90,78 @@ public class DatabaseTest {
assertTrue("Errors were caught.", rows == rowsAgain);
}
/**
*
*/
@Test
public void testInit() {
assertTrue("Database failed to init.", db.init());
}
/**
*
*/
@Test
public void testSqLiteGetConfigName() {
assertEquals("sqlite", db.getConfigName());
}
/**
*
*/
@Test
public void testSqLiteGetgName() {
assertEquals("SQLite", db.getName());
}
/**
*
*/
@Test
public void testMysqlGetConfigName() {
assertEquals("mysql", new MySQLDB(plan).getConfigName());
}
/**
*
*/
@Test
public void testMysqlGetName() {
assertEquals("MySQL", new MySQLDB(plan).getName());
}
/**
* @throws SQLException
*/
@Ignore("")
@Test // TODO Rewrite
public void testRemoveAll() throws SQLException {
db.init();
//UserData data = MockUtils.mockUser();
//db.saveUserData(data);
HashMap<String, Integer> c = new HashMap<>();
c.put("/plan", 1);
c.put("/tp", 4);
c.put("/pla", 7);
c.put("/help", 21);
c.put("/roiergbnougbierubieugbeigubeigubgierbgeugeg", 3);
db.saveCommandUse(c);
assertTrue(db.removeAllData());
assertTrue("Contains the user", db.getUserDataForUUIDS(Arrays.asList(MockUtils.getPlayerUUID(), MockUtils.getPlayer2UUID())).isEmpty());
assertTrue("Contains commandUse", db.getCommandUse().isEmpty());
}
/**
* @throws SQLException
*/
@Ignore("//TODO")
@Test
public void testSaveCommandUse() throws SQLException {
db.init();
HashMap<String, Integer> c = new HashMap<>();
c.put("/plan", 1);
c.put("/tp", 4);
c.put("/pla", 7);
c.put("/help", 21);
c.put("/roiergbnougbierubieugbeigubeigubgierbgeugeg", 3);
db.saveCommandUse(c);
c.remove("/roiergbnougbierubieugbeigubeigubgierbgeugeg");
Map<String, Integer> expected = new HashMap<>();
expected.put("plan", 1);
expected.put("tp", 4);
expected.put("pla", 7);
expected.put("help", 21);
expected.put("roiergbnougbierubieugbeigubeigubgierbgeugeg", 3);
db.saveCommandUse(expected);
expected.remove("roiergbnougbierubieugbeigubeigubgierbgeugeg");
Map<String, Integer> commandUse = db.getCommandUse();
assertEquals(c, commandUse);
c.put("/test", 3);
c.put("/tp", 6);
c.put("/pla", 4);
db.saveCommandUse(c);
c.put("/pla", 7);
assertEquals(expected, commandUse);
expected.put("test", 3);
expected.put("tp", 6);
expected.put("pla", 4);
db.saveCommandUse(expected);
expected.put("pla", 7);
commandUse = db.getCommandUse();
assertEquals(c, commandUse);
assertEquals(expected, commandUse);
}
/**
* @throws SQLException
*/
@Test // TODO Rewrite
public void testRemove() throws SQLException {
/*
db.init();
UserData data = MockUtils.mockUser();
db.saveUserData(data);
assertTrue(db.removeAccount(data.getUuid().toString()));
assertTrue("Contains the user", !db.wasSeenBefore(data.getUuid()));
*/
}
/**
* @throws SQLException
*/
@Test
@Ignore("Backup has to be rewritten")
public void testBackup() throws SQLException {
}
/**
* @throws SQLException
*/
// Big test because
@Test
@Ignore("Backup has to be rewritten")
public void testRestore() throws SQLException {
public void testCommandUseTableIDSystem() throws SQLException {
Map<String, Integer> save = new HashMap<>();
save.put("plan", 1);
save.put("tp", 4);
save.put("pla", 7);
save.put("help", 21);
save.put("roiergbnougbierubieugbeigubeigubgierbgeugeg", 3);
db.saveCommandUse(save);
CommandUseTable commandUseTable = db.getCommandUseTable();
Optional<Integer> id = commandUseTable.getCommandID("plan");
assertTrue(id.isPresent());
Optional<String> commandByID = commandUseTable.getCommandByID(id.get());
assertTrue(commandByID.isPresent());
assertEquals("plan", commandByID.get());
assertFalse(commandUseTable.getCommandID("roiergbnougbierubieugbeigubeigubgierbgeugeg").isPresent());
}
@Test
@ -229,8 +185,431 @@ public class DatabaseTest {
expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded));
expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded));
tpsTable.saveTPSData(expected);
for (TPS tps : expected) {
tpsTable.insertTPS(tps);
}
assertEquals(expected, tpsTable.getTPSData());
}
private void saveUserOne() throws SQLException {
db.getUsersTable().registerUser(uuid, 123456789L, "Test");
}
private void saveUserTwo() throws SQLException {
db.getUsersTable().registerUser(uuid2, 123456789L, "Test");
}
@Test
public void testActionsTable() throws SQLException {
saveUserOne();
ActionsTable actionsTable = db.getActionsTable();
Action save = new Action(234567890L, Actions.REGISTERED, "Additional Info");
Action expected = new Action(234567890L, Actions.REGISTERED, "Additional Info", 1);
actionsTable.insertAction(uuid, save);
List<Action> actions = actionsTable.getActions(uuid);
assertEquals(expected, actions.get(0));
}
@Test
public void testIPTable() throws SQLException {
saveUserOne();
IPsTable ipsTable = db.getIpsTable();
String expectedIP = "1.2.3.4";
String expectedGeoLoc = "TestLocation";
ipsTable.saveIP(uuid, expectedIP, expectedGeoLoc);
ipsTable.saveIP(uuid, expectedIP, expectedGeoLoc);
List<String> ips = ipsTable.getIps(uuid);
assertEquals(1, ips.size());
assertEquals(expectedIP, ips.get(0));
List<String> geolocations = ipsTable.getGeolocations(uuid);
assertEquals(1, geolocations.size());
assertEquals(expectedGeoLoc, geolocations.get(0));
Optional<String> result = ipsTable.getGeolocation(expectedIP);
assertTrue(result.isPresent());
assertEquals(expectedGeoLoc, result.get());
}
@Test // Does not test getting sessions from another server.
public void testNicknamesTable() throws SQLException {
saveUserOne();
NicknamesTable nickTable = db.getNicknamesTable();
String expected = "TestNickname";
nickTable.saveUserName(uuid, expected);
nickTable.saveUserName(uuid, expected);
List<String> nicknames = nickTable.getNicknames(uuid);
assertEquals(1, nicknames.size());
assertEquals(expected, nicknames.get(0));
List<String> allNicknames = nickTable.getAllNicknames(uuid);
assertEquals(nicknames, allNicknames);
}
@Test
public void testSecurityTable() throws SQLException {
SecurityTable securityTable = db.getSecurityTable();
WebUser expected = new WebUser("Test", "RandomGarbageBlah", 0);
securityTable.addNewUser(expected);
assertTrue(securityTable.userExists("Test"));
WebUser test = securityTable.getWebUser("Test");
assertEquals(expected, test);
assertFalse(securityTable.userExists("NotExist"));
assertNull(securityTable.getWebUser("NotExist"));
assertEquals(1, securityTable.getUsers().size());
securityTable.removeUser("Test");
assertFalse(securityTable.userExists("Test"));
assertNull(securityTable.getWebUser("Test"));
assertEquals(0, securityTable.getUsers().size());
}
@Test
public void testWorldTable() throws SQLException {
WorldTable worldTable = db.getWorldTable();
List<String> worlds = Arrays.asList("Test", "Test2", "Test3");
worldTable.saveWorlds(worlds);
List<String> saved = worldTable.getWorlds();
assertEquals(worlds, saved);
}
private void saveTwoWorlds() throws SQLException {
db.getWorldTable().saveWorlds(worlds);
}
private WorldTimes createWorldTimes() {
Map<String, GMTimes> times = new HashMap<>();
Map<String, Long> gm = new HashMap<>();
String[] gms = GMTimes.getGMKeyArray();
gm.put(gms[0], 1000L);
gm.put(gms[1], 2000L);
gm.put(gms[2], 3000L);
gm.put(gms[3], 4000L);
times.put(worlds.get(0), new GMTimes(gm));
return new WorldTimes(times);
}
private List<KillData> createKills() {
List<KillData> kills = new ArrayList<>();
kills.add(new KillData(uuid2, "Iron Sword", 4321L));
kills.add(new KillData(uuid2, "Gold Sword", 5321L));
return kills;
}
@Test
public void testSessionPlaytimeSaving() throws SQLException {
saveTwoWorlds();
saveUserOne();
saveUserTwo();
Session session = new Session(12345L, "", "");
session.endSession(22345L);
session.setWorldTimes(createWorldTimes());
session.setPlayerKills(createKills());
long expectedLength = 10000L;
assertEquals(expectedLength, session.getLength());
assertEquals(expectedLength, session.getWorldTimes().getTotal());
SessionsTable sessionsTable = db.getSessionsTable();
sessionsTable.saveSession(uuid, session);
assertEquals(expectedLength, sessionsTable.getPlaytime(uuid));
assertEquals(0L, sessionsTable.getPlaytime(uuid, 30000L));
long playtimeOfServer = sessionsTable.getPlaytimeOfServer(TestInit.getServerUUID());
assertEquals(expectedLength, playtimeOfServer);
assertEquals(0L, sessionsTable.getPlaytimeOfServer(TestInit.getServerUUID(), 30000L));
assertEquals(1, sessionsTable.getSessionCount(uuid));
assertEquals(0, sessionsTable.getSessionCount(uuid, 30000L));
}
@Test
public void testSessionSaving() throws SQLException {
saveTwoWorlds();
saveUserOne();
saveUserTwo();
Session session = new Session(12345L, "", "");
session.endSession(22345L);
session.setWorldTimes(createWorldTimes());
session.setPlayerKills(createKills());
SessionsTable sessionsTable = db.getSessionsTable();
sessionsTable.saveSession(uuid, session);
Map<String, List<Session>> sessions = sessionsTable.getSessions(uuid);
for (Map.Entry<String, List<Session>> entry : sessions.entrySet()) {
String key = entry.getKey();
if (key == null) {
System.out.print("null");
} else if (key.isEmpty()) {
System.out.print("empty");
} else {
System.out.print(key);
}
System.out.println(" " + entry.getValue());
}
List<Session> savedSessions = sessions.get("ServerName");
assertNotNull(savedSessions);
assertEquals(1, savedSessions.size());
assertNull(sessions.get(worlds.get(1)));
assertEquals(session, savedSessions.get(0));
}
@Test
public void testUserInfoTableRegisterUnRegistered() throws SQLException {
UserInfoTable userInfoTable = db.getUserInfoTable();
assertFalse(userInfoTable.isRegistered(uuid));
UsersTable usersTable = db.getUsersTable();
assertFalse(usersTable.isRegistered(uuid));
userInfoTable.registerUserInfo(uuid, 123456789L);
assertTrue(usersTable.isRegistered(uuid));
assertTrue(userInfoTable.isRegistered(uuid));
UserInfo userInfo = userInfoTable.getUserInfo(uuid);
assertEquals(uuid, userInfo.getUuid());
assertEquals(123456789L, (long) usersTable.getRegisterDates().get(0));
assertEquals(123456789L, userInfo.getRegistered());
assertEquals("Waiting for Update..", userInfo.getName());
assertFalse(userInfo.isBanned());
assertFalse(userInfo.isOpped());
}
@Test
public void testUserInfoTableRegisterRegistered() throws SQLException {
saveUserOne();
UsersTable usersTable = db.getUsersTable();
assertTrue(usersTable.isRegistered(uuid));
UserInfoTable userInfoTable = db.getUserInfoTable();
assertFalse(userInfoTable.isRegistered(uuid));
userInfoTable.registerUserInfo(uuid, 223456789L);
assertTrue(usersTable.isRegistered(uuid));
assertTrue(userInfoTable.isRegistered(uuid));
UserInfo userInfo = userInfoTable.getUserInfo(uuid);
assertEquals(uuid, userInfo.getUuid());
assertEquals(123456789L, (long) usersTable.getRegisterDates().get(0));
assertEquals(223456789L, userInfo.getRegistered());
assertEquals("Test", userInfo.getName());
assertFalse(userInfo.isBanned());
assertFalse(userInfo.isOpped());
assertEquals(userInfo, userInfoTable.getAllUserInfo().get(0));
}
@Test
public void testUserInfoTableUpdateBannedOpped() throws SQLException {
UserInfoTable userInfoTable = db.getUserInfoTable();
userInfoTable.registerUserInfo(uuid, 223456789L);
assertTrue(userInfoTable.isRegistered(uuid));
userInfoTable.updateOpAndBanStatus(uuid, true, true);
UserInfo userInfo = userInfoTable.getUserInfo(uuid);
assertTrue(userInfo.isBanned());
assertTrue(userInfo.isOpped());
userInfoTable.updateOpAndBanStatus(uuid, false, true);
userInfo = userInfoTable.getUserInfo(uuid);
assertTrue(userInfo.isBanned());
assertFalse(userInfo.isOpped());
userInfoTable.updateOpAndBanStatus(uuid, false, false);
userInfo = userInfoTable.getUserInfo(uuid);
assertFalse(userInfo.isBanned());
assertFalse(userInfo.isOpped());
}
@Test
public void testUsersTableUpdateName() throws SQLException {
saveUserOne();
UsersTable usersTable = db.getUsersTable();
assertEquals(uuid, usersTable.getUuidOf("Test"));
usersTable.updateName(uuid, "NewName");
assertNull(usersTable.getUuidOf("Test"));
assertEquals("NewName", usersTable.getPlayerName(uuid));
assertEquals(uuid, usersTable.getUuidOf("NewName"));
}
@Test
public void testUsersTableKickSaving() throws SQLException {
saveUserOne();
UsersTable usersTable = db.getUsersTable();
assertEquals(0, usersTable.getTimesKicked(uuid));
int random = new Random().nextInt(20);
for (int i = 0; i < random + 1; i++) {
usersTable.kicked(uuid);
}
assertEquals(random + 1, usersTable.getTimesKicked(uuid));
}
@Test
public void testRemovalSingleUser() throws SQLException {
saveUserTwo();
UserInfoTable userInfoTable = db.getUserInfoTable();
UsersTable usersTable = db.getUsersTable();
SessionsTable sessionsTable = db.getSessionsTable();
NicknamesTable nicknamesTable = db.getNicknamesTable();
IPsTable ipsTable = db.getIpsTable();
ActionsTable actionsTable = db.getActionsTable();
userInfoTable.registerUserInfo(uuid, 223456789L);
saveTwoWorlds();
Session session = new Session(12345L, "", "");
session.endSession(22345L);
session.setWorldTimes(createWorldTimes());
session.setPlayerKills(createKills());
sessionsTable.saveSession(uuid, session);
nicknamesTable.saveUserName(uuid, "TestNick");
ipsTable.saveIP(uuid, "1.2.3.4", "TestLoc");
actionsTable.insertAction(uuid, new Action(1324L, Actions.REGISTERED, "Add"));
assertTrue(usersTable.isRegistered(uuid));
db.removeAccount(uuid);
assertFalse(usersTable.isRegistered(uuid));
assertFalse(userInfoTable.isRegistered(uuid));
assertTrue(nicknamesTable.getNicknames(uuid).isEmpty());
assertTrue(ipsTable.getGeolocations(uuid).isEmpty());
assertTrue(ipsTable.getIps(uuid).isEmpty());
assertTrue(sessionsTable.getSessions(uuid).isEmpty());
assertTrue(actionsTable.getActions(uuid).isEmpty());
}
@Test
public void testRemovalEverything() throws SQLException {
saveUserTwo();
UserInfoTable userInfoTable = db.getUserInfoTable();
UsersTable usersTable = db.getUsersTable();
SessionsTable sessionsTable = db.getSessionsTable();
NicknamesTable nicknamesTable = db.getNicknamesTable();
IPsTable ipsTable = db.getIpsTable();
ActionsTable actionsTable = db.getActionsTable();
userInfoTable.registerUserInfo(uuid, 223456789L);
saveTwoWorlds();
Session session = new Session(12345L, "", "");
session.endSession(22345L);
session.setWorldTimes(createWorldTimes());
session.setPlayerKills(createKills());
sessionsTable.saveSession(uuid, session);
nicknamesTable.saveUserName(uuid, "TestNick");
ipsTable.saveIP(uuid, "1.2.3.4", "TestLoc");
actionsTable.insertAction(uuid, new Action(1324L, Actions.REGISTERED, "Add"));
assertTrue(usersTable.isRegistered(uuid));
Map<String, Integer> save = new HashMap<>();
save.put("plan", 1);
save.put("tp", 4);
save.put("pla", 7);
save.put("help", 21);
db.saveCommandUse(save);
TPSTable tpsTable = db.getTpsTable();
List<TPS> expected = new ArrayList<>();
Random r = new Random();
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
int availableProcessors = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
final double averageCPUUsage = MathUtils.round(operatingSystemMXBean.getSystemLoadAverage() / availableProcessors * 100.0);
final long usedMemory = 51231251254L;
final int entityCount = 6123;
final int chunksLoaded = 2134;
expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded));
expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded));
expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded));
expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded));
for (TPS tps : expected) {
tpsTable.insertTPS(tps);
}
SecurityTable securityTable = db.getSecurityTable();
securityTable.addNewUser(new WebUser("Test", "RandomGarbageBlah", 0));
db.removeAllData();
assertFalse(usersTable.isRegistered(uuid));
assertFalse(usersTable.isRegistered(uuid2));
assertFalse(userInfoTable.isRegistered(uuid));
assertTrue(nicknamesTable.getNicknames(uuid).isEmpty());
assertTrue(ipsTable.getGeolocations(uuid).isEmpty());
assertTrue(ipsTable.getIps(uuid).isEmpty());
assertTrue(sessionsTable.getSessions(uuid).isEmpty());
assertTrue(actionsTable.getActions(uuid).isEmpty());
assertTrue(db.getCommandUse().isEmpty());
assertTrue(db.getWorldTable().getWorlds().isEmpty());
assertTrue(tpsTable.getTPSData().isEmpty());
assertTrue(db.getServerTable().getBukkitServers().isEmpty());
assertTrue(securityTable.getUsers().isEmpty());
}
@Test
public void testServerTableBungeeSave() throws SQLException {
ServerTable serverTable = db.getServerTable();
Optional<ServerInfo> bungeeInfo = serverTable.getBungeeInfo();
assertFalse(bungeeInfo.isPresent());
UUID bungeeUUID = UUID.randomUUID();
ServerInfo bungeeCord = new ServerInfo(-1, bungeeUUID, "BungeeCord", "Random:1234");
serverTable.saveCurrentServerInfo(bungeeCord);
bungeeCord.setId(2);
bungeeInfo = serverTable.getBungeeInfo();
assertTrue(bungeeInfo.isPresent());
assertEquals(bungeeCord, bungeeInfo.get());
Optional<Integer> serverID = serverTable.getServerID(bungeeUUID);
assertTrue(serverID.isPresent());
assertEquals(2, (int) serverID.get());
}
@Test
public void testServerTableBungee() throws SQLException {
testServerTableBungeeSave();
ServerTable serverTable = db.getServerTable();
List<ServerInfo> bukkitServers = serverTable.getBukkitServers();
assertEquals(1, bukkitServers.size());
}
}

View File

@ -2,7 +2,7 @@ package test.java.main.java.com.djrapitops.plan.utilities.comparators;
import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.UserInfo;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.locale.Message;
import main.java.com.djrapitops.plan.locale.Msg;
@ -52,23 +52,23 @@ public class ComparatorTest {
@Test
public void testUserDataLastPlayedComparator() {
List<UserData> test = RandomData.randomUserData();
List<Long> longValues = test.stream().map(UserData::getLastPlayed).collect(Collectors.toList());
List<UserInfo> test = RandomData.randomUserData();
List<Long> longValues = test.stream().map(UserInfo::getLastSeen).collect(Collectors.toList());
longValues.sort(Long::compare);
Collections.reverse(longValues);
test.sort(new UserDataLastPlayedComparator());
List<Long> afterSort = test.stream().map(UserData::getLastPlayed).collect(Collectors.toList());
List<Long> afterSort = test.stream().map(UserInfo::getLastSeen).collect(Collectors.toList());
assertEquals(longValues, afterSort);
}
@Test
public void testUserDataNameComparator() {
List<UserData> test = RandomData.randomUserData();
List<String> stringValues = test.stream().map(UserData::getName).collect(Collectors.toList());
List<UserInfo> test = RandomData.randomUserData();
List<String> stringValues = test.stream().map(UserInfo::getName).collect(Collectors.toList());
Collections.sort(stringValues);
test.sort(new UserDataNameComparator());
List<String> afterSort = test.stream().map(UserData::getName).collect(Collectors.toList());
List<String> afterSort = test.stream().map(UserInfo::getName).collect(Collectors.toList());
assertEquals(stringValues, afterSort);
}

View File

@ -2,7 +2,7 @@ package test.java.utils;
import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.UserInfo;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.utilities.PassEncryptUtil;
import main.java.com.djrapitops.plan.utilities.analysis.Point;
@ -22,7 +22,7 @@ public class RandomData {
}
public static String randomString(int size) {
return RandomStringUtils.random(size);
return RandomStringUtils.randomAlphanumeric(size);
}
public static List<WebUser> randomWebUsers() throws PassEncryptUtil.CannotPerformOperationException {
@ -64,7 +64,7 @@ public class RandomData {
return clazz.getEnumConstants()[x];
}
public static List<UserData> randomUserData() {
public static List<UserInfo> randomUserData() {
return new ArrayList<>();
// TODO Rewrite
}

View File

@ -12,6 +12,7 @@ import com.djrapitops.plugin.utilities.player.Fetch;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.ServerVariableHolder;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.server.ServerInfoManager;
import main.java.com.djrapitops.plan.locale.Locale;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
@ -23,6 +24,8 @@ import org.powermock.api.mockito.PowerMockito;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;
import java.util.logging.Logger;
import static org.powermock.api.mockito.PowerMockito.when;
@ -33,10 +36,8 @@ import static org.powermock.api.mockito.PowerMockito.when;
public class TestInit {
private Plan planMock;
private static final UUID serverUUID = UUID.fromString("9a27457b-f1a2-4b71-be7f-daf2170a1b66");
/**
*
*/
public TestInit() {
}
@ -67,8 +68,6 @@ public class TestInit {
}
private void setUp() throws Exception {
clean();
planMock = PowerMockito.mock(Plan.class);
StaticHolder.setInstance(Plan.class, planMock);
StaticHolder.setInstance(planMock.getClass(), planMock);
@ -103,6 +102,10 @@ public class TestInit {
when(planMock.benchmark()).thenReturn(bench);
when(planMock.getVariable()).thenReturn(serverVariableHolder);
when(planMock.fetch()).thenReturn(fetch);
ServerInfoManager serverInfoManager = PowerMockito.mock(ServerInfoManager.class);
when(serverInfoManager.getServerUUID()).thenReturn(serverUUID);
when(planMock.getServerInfoManager()).thenReturn(serverInfoManager);
RunnableFactory<Plan> runnableFactory = mockRunnableFactory();
when(planMock.getRunnableFactory()).thenReturn(runnableFactory);
ColorScheme cs = new ColorScheme(ChatColor.BLACK, ChatColor.BLACK, ChatColor.BLACK, ChatColor.BLACK);
@ -196,15 +199,7 @@ public class TestInit {
return planMock;
}
public static void clean() throws IOException {
File testFolder = getTestFolder();
if (!testFolder.exists() || !testFolder.isDirectory()) {
return;
}
for (File f : testFolder.listFiles()) {
f.delete();
}
public static UUID getServerUUID() {
return serverUUID;
}
}