Sort out player join address things

Applied some thought to how this stuff should work.
- nulls now possible in the column when value is not available
- Called "Join addresses" instead of hostnames
- Remove bogus data with a patch

- Proper hostname method for spigot
- Removed method calls from nukkit since there was nothing that sounded
  proper

Affects:
- Close #1798 (Copied all code over)
This commit is contained in:
Risto Lahtela 2021-03-17 11:31:14 +02:00
parent 443cb65274
commit 2bc15db6d0
36 changed files with 442 additions and 195 deletions

View File

@ -173,9 +173,9 @@ public abstract class BukkitImporter implements Importer {
long registered = userImportData.getRegistered();
boolean op = userImportData.isOp();
boolean banned = userImportData.isBanned();
String hostname = userImportData.getHostname();
String joinAddress = userImportData.getJoinAddress();
return new UserInfo(uuid, serverUUID.get(), registered, op, hostname, banned);
return new UserInfo(uuid, serverUUID.get(), registered, op, joinAddress, banned);
}
private FinishedSession toSession(UserImportData userImportData) {

View File

@ -50,6 +50,8 @@ import org.bukkit.event.player.PlayerQuitEvent;
import javax.inject.Inject;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
@ -75,6 +77,7 @@ public class PlayerOnlineListener implements Listener {
private final Status status;
private final AtomicBoolean virtualHostMethodAvailable = new AtomicBoolean(true);
private final Map<UUID, String> joinAddresses;
@Inject
public PlayerOnlineListener(
@ -101,6 +104,8 @@ public class PlayerOnlineListener implements Listener {
this.sessionCache = sessionCache;
this.status = status;
this.errorLogger = errorLogger;
joinAddresses = new HashMap<>();
}
@EventHandler(priority = EventPriority.MONITOR)
@ -110,6 +115,10 @@ public class PlayerOnlineListener implements Listener {
UUID playerUUID = event.getPlayer().getUniqueId();
boolean operator = event.getPlayer().isOp();
boolean banned = result == PlayerLoginEvent.Result.KICK_BANNED;
String joinAddress = event.getHostname();
if (!joinAddress.isEmpty()) {
joinAddresses.put(playerUUID, joinAddress.substring(0, joinAddress.indexOf(":")));
}
dbSystem.getDatabase().executeTransaction(new BanStatusTransaction(playerUUID, () -> banned));
dbSystem.getDatabase().executeTransaction(new OperatorStatusTransaction(playerUUID, operator));
} catch (Exception e) {
@ -207,7 +216,7 @@ public class PlayerOnlineListener implements Listener {
virtualHostMethodAvailable.set(false);
}
}
return player.getAddress().getHostName();
return joinAddresses.get(player.getUniqueId());
}
@EventHandler(priority = EventPriority.NORMAL)
@ -235,6 +244,7 @@ public class PlayerOnlineListener implements Listener {
BukkitAFKListener.afkTracker.loggedOut(playerUUID, time);
joinAddresses.remove(playerUUID);
nicknameCache.removeDisplayName(playerUUID);
dbSystem.getDatabase().executeTransaction(new BanStatusTransaction(playerUUID, player::isBanned));

View File

@ -125,7 +125,7 @@ public class NetworkPageExporter extends FileExporter {
"graph?type=uniqueAndNew",
"graph?type=hourlyUniqueAndNew",
"graph?type=serverPie",
"graph?type=hostnamePie",
"graph?type=joinAddressPie",
"graph?type=activity",
"graph?type=geolocation",
"graph?type=uniqueAndNew",

View File

@ -147,7 +147,7 @@ public class ServerPageExporter extends FileExporter {
"graph?type=geolocation&server=" + serverUUID,
"graph?type=uniqueAndNew&server=" + serverUUID,
"graph?type=hourlyUniqueAndNew&server=" + serverUUID,
"graph?type=hostnamePie&server=" + serverUUID,
"graph?type=joinAddressPie&server=" + serverUUID,
"graph?type=serverCalendar&server=" + serverUUID,
"graph?type=punchCard&server=" + serverUUID,
"players?server=" + serverUUID,

View File

@ -37,6 +37,8 @@ import com.djrapitops.plan.settings.config.PlanConfig;
import com.djrapitops.plan.settings.config.paths.DataGatheringSettings;
import com.djrapitops.plan.settings.config.paths.DisplaySettings;
import com.djrapitops.plan.settings.config.paths.TimeSettings;
import com.djrapitops.plan.settings.locale.Locale;
import com.djrapitops.plan.settings.locale.lang.GenericLang;
import com.djrapitops.plan.settings.theme.Theme;
import com.djrapitops.plan.settings.theme.ThemeVal;
import com.djrapitops.plan.storage.database.DBSystem;
@ -66,6 +68,7 @@ import java.util.concurrent.TimeUnit;
public class GraphJSONCreator {
private final PlanConfig config;
private final Locale locale;
private final Theme theme;
private final DBSystem dbSystem;
private final Graphs graphs;
@ -73,11 +76,13 @@ public class GraphJSONCreator {
@Inject
public GraphJSONCreator(
PlanConfig config,
Locale locale,
Theme theme,
DBSystem dbSystem,
Graphs graphs
) {
this.config = config;
this.locale = locale;
this.theme = theme;
this.dbSystem = dbSystem;
this.graphs = graphs;
@ -412,21 +417,33 @@ public class GraphJSONCreator {
public Map<String, Object> playerHostnamePieJSONAsMap() {
String[] pieColors = theme.getPieColors(ThemeVal.GRAPH_WORLD_PIE);
Map<String, Integer> hostnameResults = dbSystem.getDatabase().query(UserInfoQueries.hostnameTotals());
Map<String, Integer> joinAddresses = dbSystem.getDatabase().query(UserInfoQueries.joinAddresses());
translateUnknown(joinAddresses);
return Maps.builder(String.class, Object.class)
.put("hostname_pie_colors", pieColors)
.put("hostname_pie_slices", graphs.pie().HostnamePie(hostnameResults).getSlices())
.put("colors", pieColors)
.put("slices", graphs.pie().joinAddressPie(joinAddresses).getSlices())
.build();
}
public Map<String, Object> playerHostnamePieJSONAsMap(ServerUUID serverUUID) {
String[] pieColors = theme.getPieColors(ThemeVal.GRAPH_WORLD_PIE);
Map<String, Integer> hostnameResults = dbSystem.getDatabase().query(UserInfoQueries.hostnameTotals(serverUUID));
Map<String, Integer> joinAddresses = dbSystem.getDatabase().query(UserInfoQueries.joinAddresses(serverUUID));
translateUnknown(joinAddresses);
return Maps.builder(String.class, Object.class)
.put("hostname_pie_colors", pieColors)
.put("hostname_pie_slices", graphs.pie().HostnamePie(hostnameResults).getSlices())
.put("colors", pieColors)
.put("slices", graphs.pie().joinAddressPie(joinAddresses).getSlices())
.build();
}
public void translateUnknown(Map<String, Integer> joinAddresses) {
Integer unknown = joinAddresses.get("Unknown");
if (unknown != null) {
joinAddresses.remove("Unknown");
joinAddresses.put(locale.getString(GenericLang.UNKNOWN), unknown);
}
}
}

View File

@ -20,18 +20,18 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HostnamePie extends Pie {
public class JoinAddressPie extends Pie {
HostnamePie(Map<String, Integer> hostnames) {
super(turnToSlices(hostnames));
JoinAddressPie(Map<String, Integer> joinAddresses) {
super(turnToSlices(joinAddresses));
}
private static List<PieSlice> turnToSlices(Map<String, Integer> hostnames) {
private static List<PieSlice> turnToSlices(Map<String, Integer> joinAddresses) {
List<PieSlice> slices = new ArrayList<>();
for (Map.Entry<String, Integer> server : hostnames.entrySet()) {
String hostname = server.getKey();
Integer total = server.getValue();
slices.add(new PieSlice(hostname, total));
for (Map.Entry<String, Integer> address : joinAddresses.entrySet()) {
String joinAddress = address.getKey();
Integer total = address.getValue();
slices.add(new PieSlice(joinAddress, total));
}
return slices;
}

View File

@ -68,8 +68,8 @@ public class PieGraphFactory {
return new ServerPreferencePie(serverPlaytimes);
}
public Pie HostnamePie(Map<String, Integer> hostname) {
return new HostnamePie(hostname);
public Pie joinAddressPie(Map<String, Integer> joinAddresses) {
return new JoinAddressPie(joinAddresses);
}
public WorldPie worldPie(WorldTimes worldTimes) {

View File

@ -131,7 +131,7 @@ public class GraphsJSONResolver implements Resolver {
return DataID.GRAPH_PUNCHCARD;
case "serverPie":
return DataID.GRAPH_SERVER_PIE;
case "hostnamePie":
case "joinAddressPie":
return DataID.GRAPH_HOSTNAME_PIE;
default:
throw new BadRequestException("unknown 'type' parameter.");

View File

@ -36,15 +36,15 @@ public class UserInfo {
private final long registered;
private final boolean banned;
private final boolean opped;
private final String hostname;
private final String joinAddress;
public UserInfo(UUID playerUUID, ServerUUID serverUUID, long registered, boolean opped, String hostname, boolean banned) {
public UserInfo(UUID playerUUID, ServerUUID serverUUID, long registered, boolean opped, String joinAddress, boolean banned) {
this.playerUUID = playerUUID;
this.serverUUID = serverUUID;
this.registered = registered;
this.opped = opped;
this.banned = banned;
this.hostname = hostname;
this.joinAddress = joinAddress;
}
public UUID getPlayerUuid() {
@ -55,8 +55,8 @@ public class UserInfo {
return serverUUID;
}
public String getHostname() {
return hostname;
public String getJoinAddress() {
return joinAddress;
}
public long getRegistered() {
@ -74,18 +74,19 @@ public class UserInfo {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserInfo)) return false;
if (o == null || getClass() != o.getClass()) return false;
UserInfo userInfo = (UserInfo) o;
return registered == userInfo.registered &&
banned == userInfo.banned &&
opped == userInfo.opped &&
playerUUID.equals(userInfo.playerUUID) &&
serverUUID.equals(userInfo.serverUUID);
return registered == userInfo.registered
&& banned == userInfo.banned
&& opped == userInfo.opped
&& Objects.equals(playerUUID, userInfo.playerUUID)
&& Objects.equals(serverUUID, userInfo.serverUUID)
&& Objects.equals(joinAddress, userInfo.joinAddress);
}
@Override
public int hashCode() {
return Objects.hash(playerUUID, serverUUID, registered, banned, hostname, opped);
return Objects.hash(playerUUID, serverUUID, registered, banned, joinAddress, opped);
}
@Override
@ -96,7 +97,7 @@ public class UserInfo {
", registered=" + registered +
", banned=" + banned +
", opped=" + opped +
", hostname=" + hostname +
", joinAddress=" + joinAddress +
'}';
}
}

View File

@ -45,11 +45,11 @@ public class UserImportData {
private int mobKills;
private int deaths;
private String hostname;
private String joinAddress;
private UserImportData(String name, UUID uuid, List<Nickname> nicknames, long registered, boolean op,
boolean banned, int timesKicked, List<String> ips, Map<String, GMTimes> worldTimes, List<PlayerKill> kills,
int mobKills, int deaths, String hostname) {
int mobKills, int deaths, String joinAddress) {
this.name = name;
this.uuid = uuid;
this.nicknames = nicknames;
@ -62,7 +62,7 @@ public class UserImportData {
this.kills = kills;
this.mobKills = mobKills;
this.deaths = deaths;
this.hostname = hostname;
this.joinAddress = joinAddress;
}
public static UserImportDataBuilder builder(ServerUUID serverUUID) {
@ -117,12 +117,12 @@ public class UserImportData {
this.banned = banned;
}
public void setHostname(String hostname) {
this.hostname = hostname;
public String getJoinAddress() {
return joinAddress;
}
public String getHostname() {
return hostname;
public void setJoinAddress(String joinAddress) {
this.joinAddress = joinAddress;
}
public int getTimesKicked() {
@ -173,6 +173,32 @@ public class UserImportData {
this.deaths = deaths;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserImportData)) return false;
UserImportData that = (UserImportData) o;
return registered == that.registered &&
op == that.op &&
banned == that.banned &&
timesKicked == that.timesKicked &&
mobKills == that.mobKills &&
deaths == that.deaths &&
joinAddress.equals(that.joinAddress) &&
Objects.equals(name, that.name) &&
Objects.equals(uuid, that.uuid) &&
Objects.equals(nicknames, that.nicknames) &&
Objects.equals(ips, that.ips) &&
Objects.equals(worldTimes, that.worldTimes) &&
Objects.equals(kills, that.kills);
}
@Override
public int hashCode() {
return Objects.hash(name, uuid, nicknames, registered, op, banned, timesKicked, ips,
worldTimes, kills, mobKills, deaths, joinAddress);
}
public static final class UserImportDataBuilder {
private final ServerUUID serverUUID;
@ -188,7 +214,7 @@ public class UserImportData {
private int timesKicked;
private int mobKills;
private int deaths;
private String hostname;
private String joinAddress;
private UserImportDataBuilder(ServerUUID serverUUID) {
this.serverUUID = serverUUID;
@ -300,33 +326,7 @@ public class UserImportData {
public UserImportData build() {
return new UserImportData(name, uuid, nicknames, registered, op, banned, timesKicked, ips,
worldTimes, kills, mobKills, deaths, hostname);
worldTimes, kills, mobKills, deaths, joinAddress);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserImportData)) return false;
UserImportData that = (UserImportData) o;
return registered == that.registered &&
op == that.op &&
banned == that.banned &&
timesKicked == that.timesKicked &&
mobKills == that.mobKills &&
deaths == that.deaths &&
hostname.equals(that.hostname) &&
Objects.equals(name, that.name) &&
Objects.equals(uuid, that.uuid) &&
Objects.equals(nicknames, that.nicknames) &&
Objects.equals(ips, that.ips) &&
Objects.equals(worldTimes, that.worldTimes) &&
Objects.equals(kills, that.kills);
}
@Override
public int hashCode() {
return Objects.hash(name, uuid, nicknames, registered, op, banned, timesKicked, ips,
worldTimes, kills, mobKills, deaths, hostname);
}
}

View File

@ -111,6 +111,7 @@ public enum HtmlLang implements Lang {
// Playerbase overview tab
TITLE_PLAYERBASE_DEVELOPMENT("Playerbase development"),
TITLE_CURRENT_PLAYERBASE("Current Playerbase"),
TITLE_JOIN_ADDRESSES("Join Addresses"),
COMPARING_60_DAYS("Comparing 30d ago to Now"),
TITLE_30_DAYS_AGO("30 days ago"),
TITLE_NOW("Now"),

View File

@ -173,7 +173,8 @@ public abstract class SQLDB extends AbstractDatabase {
new LinkUsersToPlayersSecurityTablePatch(),
new LitebansTableHeaderPatch(),
new UserInfoHostnamePatch(),
new ServerIsProxyPatch()
new ServerIsProxyPatch(),
new UserInfoHostnameAllowNullPatch()
};
}

View File

@ -184,7 +184,7 @@ public class DataStoreQueries {
* @param serverUUID UUID of the Plan server.
* @return Executable, use inside a {@link com.djrapitops.plan.storage.database.transactions.Transaction}
*/
public static Executable registerUserInfo(UUID playerUUID, long registered, ServerUUID serverUUID, String hostname) {
public static Executable registerUserInfo(UUID playerUUID, long registered, ServerUUID serverUUID, String joinAddress) {
return new ExecStatement(UserInfoTable.INSERT_STATEMENT) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
@ -192,7 +192,7 @@ public class DataStoreQueries {
statement.setLong(2, registered);
statement.setString(3, serverUUID.toString());
statement.setBoolean(4, false); // Banned
statement.setString(5, hostname); // Hostname
statement.setString(5, joinAddress);
statement.setBoolean(6, false); // Operator
}
};
@ -297,14 +297,14 @@ public class DataStoreQueries {
};
}
public static Executable updateHostname(UUID playerUUID, String hostname) {
public static Executable updateJoinAddress(UUID playerUUID, String joinAddress) {
String sql = "UPDATE " + UserInfoTable.TABLE_NAME + " SET " +
UserInfoTable.HOSTNAME + "=?" +
UserInfoTable.JOIN_ADDRESS + "=?" +
WHERE + UserInfoTable.USER_UUID + "=?";
return new ExecStatement(sql) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, hostname);
statement.setString(1, joinAddress);
statement.setString(2, playerUUID.toString());
}
};

View File

@ -214,7 +214,7 @@ public class LargeStoreQueries {
statement.setLong(2, user.getRegistered());
statement.setString(3, serverUUID.toString());
statement.setBoolean(4, user.isBanned());
statement.setString(5, user.getHostname());
statement.setString(5, user.getJoinAddress());
statement.setBoolean(6, user.isOperator());
statement.addBatch();
}

View File

@ -56,7 +56,7 @@ public class UserInfoQueries {
UserInfoTable.OP + ',' +
UserInfoTable.USER_UUID + ',' +
UserInfoTable.SERVER_UUID + ',' +
UserInfoTable.HOSTNAME +
UserInfoTable.JOIN_ADDRESS +
FROM + UserInfoTable.TABLE_NAME;
return new QueryAllStatement<Map<ServerUUID, List<UserInfo>>>(sql, 50000) {
@ -72,9 +72,9 @@ public class UserInfoQueries {
long registered = set.getLong(UserInfoTable.REGISTERED);
boolean banned = set.getBoolean(UserInfoTable.BANNED);
boolean op = set.getBoolean(UserInfoTable.OP);
String hostname = set.getString(UserInfoTable.HOSTNAME);
String joinAddress = set.getString(UserInfoTable.JOIN_ADDRESS);
userInfos.add(new UserInfo(uuid, serverUUID, registered, op, hostname, banned));
userInfos.add(new UserInfo(uuid, serverUUID, registered, op, joinAddress, banned));
}
return serverMap;
}
@ -93,7 +93,7 @@ public class UserInfoQueries {
UserInfoTable.BANNED + ',' +
UserInfoTable.OP + ',' +
UserInfoTable.SERVER_UUID + ',' +
UserInfoTable.HOSTNAME +
UserInfoTable.JOIN_ADDRESS +
FROM + UserInfoTable.TABLE_NAME +
WHERE + UserInfoTable.TABLE_NAME + '.' + UserInfoTable.USER_UUID + "=?";
@ -111,9 +111,9 @@ public class UserInfoQueries {
boolean op = set.getBoolean(UserInfoTable.OP);
boolean banned = set.getBoolean(UserInfoTable.BANNED);
ServerUUID serverUUID = ServerUUID.fromString(set.getString(UserInfoTable.SERVER_UUID));
String hostname = set.getString(UserInfoTable.HOSTNAME);
String joinAddress = set.getString(UserInfoTable.JOIN_ADDRESS);
userInformation.add(new UserInfo(playerUUID, serverUUID, registered, op, hostname, banned));
userInformation.add(new UserInfo(playerUUID, serverUUID, registered, op, joinAddress, banned));
}
return userInformation;
}
@ -130,7 +130,7 @@ public class UserInfoQueries {
String sql = SELECT +
UserInfoTable.REGISTERED + ',' +
UserInfoTable.BANNED + ',' +
UserInfoTable.HOSTNAME + ',' +
UserInfoTable.JOIN_ADDRESS + ',' +
UserInfoTable.OP + ',' +
UserInfoTable.USER_UUID + ',' +
UserInfoTable.SERVER_UUID +
@ -154,9 +154,9 @@ public class UserInfoQueries {
boolean banned = set.getBoolean(UserInfoTable.BANNED);
boolean op = set.getBoolean(UserInfoTable.OP);
String hostname = set.getString(UserInfoTable.HOSTNAME);
String joinAddress = set.getString(UserInfoTable.JOIN_ADDRESS);
userInformation.put(uuid, new UserInfo(uuid, serverUUID, registered, op, hostname, banned));
userInformation.put(uuid, new UserInfo(uuid, serverUUID, registered, op, joinAddress, banned));
}
return userInformation;
}
@ -194,48 +194,54 @@ public class UserInfoQueries {
};
}
public static Query<Map<String, Integer>> hostnameTotals() {
public static Query<Map<String, Integer>> joinAddresses() {
String sql = SELECT +
"COUNT(hostname) as total," +
UserInfoTable.HOSTNAME +
"COUNT(1) as total," +
"COALESCE(" + UserInfoTable.JOIN_ADDRESS + ", ?) as address" +
FROM + UserInfoTable.TABLE_NAME +
GROUP_BY + UserInfoTable.HOSTNAME +
ORDER_BY + UserInfoTable.HOSTNAME + " DESC";
return new QueryAllStatement<Map<String, Integer>>(sql, 100) {
@Override
public Map<String, Integer> processResults(ResultSet set) throws SQLException {
Map<String, Integer> hostnames = new HashMap<>();
while (set.next()) {
hostnames.put(set.getString(UserInfoTable.HOSTNAME), set.getInt("total"));
}
return hostnames;
}
};
}
public static Query<Map<String, Integer>> hostnameTotals(ServerUUID serverUUID) {
String sql = SELECT +
"COUNT(hostname) as total," +
UserInfoTable.HOSTNAME +
FROM + UserInfoTable.TABLE_NAME +
GROUP_BY + UserInfoTable.HOSTNAME +
WHERE + UserInfoTable.SERVER_UUID + "=?" +
ORDER_BY + UserInfoTable.HOSTNAME + " DESC";
GROUP_BY + "address" +
ORDER_BY + "address DESC";
return new QueryStatement<Map<String, Integer>>(sql, 100) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, serverUUID.toString());
statement.setString(1, "Unknown");
}
@Override
public Map<String, Integer> processResults(ResultSet set) throws SQLException {
Map<String, Integer> hostnames = new HashMap<>();
Map<String, Integer> joinAddresses = new HashMap<>();
while (set.next()) {
hostnames.put(set.getString(UserInfoTable.HOSTNAME), set.getInt("total"));
joinAddresses.put(set.getString("address"), set.getInt("total"));
}
return hostnames;
return joinAddresses;
}
};
}
public static Query<Map<String, Integer>> joinAddresses(ServerUUID serverUUID) {
String sql = SELECT +
"COUNT(1) as total," +
"COALESCE(" + UserInfoTable.JOIN_ADDRESS + ", ?) as address" +
FROM + UserInfoTable.TABLE_NAME +
WHERE + UserInfoTable.SERVER_UUID + "=?" +
GROUP_BY + "address" +
ORDER_BY + "address DESC";
return new QueryStatement<Map<String, Integer>>(sql, 100) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, "Unknown");
statement.setString(2, serverUUID.toString());
}
@Override
public Map<String, Integer> processResults(ResultSet set) throws SQLException {
Map<String, Integer> joinAddresses = new HashMap<>();
while (set.next()) {
joinAddresses.put(set.getString("address"), set.getInt("total"));
}
return joinAddresses;
}
};
}

View File

@ -0,0 +1,83 @@
/*
* This file is part of Player Analytics (Plan).
*
* Plan is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License v3 as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Plan is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Plan. If not, see <https://www.gnu.org/licenses/>.
*/
package com.djrapitops.plan.storage.database.sql.tables;
import com.djrapitops.plan.storage.database.DBType;
import com.djrapitops.plan.storage.database.queries.Query;
import com.djrapitops.plan.storage.database.queries.QueryStatement;
import com.djrapitops.plan.storage.database.sql.building.CreateTableBuilder;
import com.djrapitops.plan.storage.database.sql.building.Sql;
import com.djrapitops.plan.storage.database.transactions.ExecStatement;
import com.djrapitops.plan.storage.database.transactions.Executable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import static com.djrapitops.plan.storage.database.sql.building.Sql.*;
public class MetadataTable {
public static final String TABLE_NAME = "plan_database_metadata";
public static final String KEY = "id";
public static final String VALUE = "uuid";
public static final String INSERT_STATEMENT = "INSERT INTO " + TABLE_NAME + " (" +
KEY + ',' +
VALUE +
") VALUES (?, ?)";
public static final String UPDATE_STATEMENT = "UPDATE " + TABLE_NAME + " SET " + VALUE + "=?" +
WHERE + KEY + "=?";
public static final String SELECT_VALUE_OF_KEY = SELECT + VALUE + FROM + TABLE_NAME + WHERE + KEY + "=?";
private MetadataTable() {
/* Static information class */
}
public static Executable insertValue(String key, String value) {
return new ExecStatement(MetadataTable.INSERT_STATEMENT) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, key);
statement.setString(2, value);
}
};
}
public static Query<String> getValueOrNull(String key) {
return new QueryStatement<String>(MetadataTable.SELECT_VALUE_OF_KEY) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, key);
}
@Override
public String processResults(ResultSet set) throws SQLException {
return set.next() ? set.getString(MetadataTable.VALUE) : null;
}
};
}
public static String createTableSQL(DBType dbType) {
return CreateTableBuilder.create(TABLE_NAME, dbType)
.column(KEY, Sql.varchar(36)).notNull()
.column(VALUE, Sql.varchar(75)).notNull()
.toString();
}
}

View File

@ -42,14 +42,14 @@ public class UserInfoTable {
public static final String REGISTERED = "registered";
public static final String OP = "opped";
public static final String BANNED = "banned";
public static final String HOSTNAME = "hostname";
public static final String JOIN_ADDRESS = "join_address";
public static final String INSERT_STATEMENT = "INSERT INTO " + TABLE_NAME + " (" +
USER_UUID + ',' +
REGISTERED + ',' +
SERVER_UUID + ',' +
BANNED + ',' +
HOSTNAME + ',' +
JOIN_ADDRESS + ',' +
OP +
") VALUES (?, ?, ?, ?, ?, ?)";
@ -62,7 +62,7 @@ public class UserInfoTable {
.column(ID, Sql.INT).primaryKey()
.column(USER_UUID, Sql.varchar(36)).notNull()
.column(SERVER_UUID, Sql.varchar(36)).notNull()
.column(HOSTNAME, Sql.varchar(255)).notNull().defaultValue("'Unknown'")
.column(JOIN_ADDRESS, Sql.varchar(255))
.column(REGISTERED, Sql.LONG).notNull()
.column(OP, Sql.BOOL).notNull().defaultValue(false)
.column(BANNED, Sql.BOOL).notNull().defaultValue(false)

View File

@ -62,11 +62,6 @@ public abstract class Transaction {
this.db = db;
this.dbType = db.getType();
if (!shouldBeExecuted()) {
success = true;
return;
}
attempts++; // Keeps track how many attempts have been made to avoid infinite recursion.
if (db.isUnderHeavyLoad()) {
@ -79,9 +74,12 @@ public abstract class Transaction {
}
try {
initializeTransaction(db);
performOperations();
if (connection != null) connection.commit();
initializeConnection(db);
if (shouldBeExecuted()) {
initializeTransaction(db);
performOperations();
if (connection != null) connection.commit();
}
success = true;
} catch (SQLException statementFail) {
manageFailure(statementFail); // Throws a DBOpException.
@ -160,15 +158,22 @@ public abstract class Transaction {
*/
protected abstract void performOperations();
private void initializeTransaction(SQLDB db) {
private void initializeConnection(SQLDB db) {
try {
this.connection = db.getConnection();
createSavePoint();
} catch (SQLException e) {
throw new DBOpException(getClass().getSimpleName() + " initialization failed: " + e.getMessage(), e);
}
}
private void initializeTransaction(SQLDB db) {
try {
createSavePoint();
} catch (SQLException e) {
throw new DBOpException(getClass().getSimpleName() + " save point initialization failed: " + e.getMessage(), e);
}
}
private void createSavePoint() throws SQLException {
try {
this.savepoint = connection.setSavepoint();

View File

@ -33,23 +33,23 @@ import java.util.function.Supplier;
public class PlayerServerRegisterTransaction extends PlayerRegisterTransaction {
private final ServerUUID serverUUID;
private final Supplier<String> hostname;
private final Supplier<String> getJoinAddress;
public PlayerServerRegisterTransaction(UUID playerUUID, LongSupplier registered,
String playerName, ServerUUID serverUUID, Supplier<String> hostname) {
String playerName, ServerUUID serverUUID, Supplier<String> getJoinAddress) {
super(playerUUID, registered, playerName);
this.serverUUID = serverUUID;
this.hostname = hostname;
this.getJoinAddress = getJoinAddress;
}
@Override
protected void performOperations() {
super.performOperations();
long registerDate = registered.getAsLong();
String hostname = this.hostname.get();
String joinAddress = this.getJoinAddress.get();
if (Boolean.FALSE.equals(query(PlayerFetchQueries.isPlayerRegisteredOnServer(playerUUID, serverUUID)))) {
execute(DataStoreQueries.registerUserInfo(playerUUID, registerDate, serverUUID, hostname));
execute(DataStoreQueries.registerUserInfo(playerUUID, registerDate, serverUUID, joinAddress));
}
// Updates register date to smallest possible value.
@ -58,6 +58,6 @@ public class PlayerServerRegisterTransaction extends PlayerRegisterTransaction {
execute(DataStoreQueries.updateMainRegisterDate(playerUUID, registerDate));
}
execute(DataStoreQueries.updateHostname(playerUUID, hostname));
execute(DataStoreQueries.updateJoinAddress(playerUUID, joinAddress));
}
}

View File

@ -0,0 +1,82 @@
/*
* This file is part of Player Analytics (Plan).
*
* Plan is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License v3 as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Plan is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Plan. If not, see <https://www.gnu.org/licenses/>.
*/
package com.djrapitops.plan.storage.database.transactions.patches;
import com.djrapitops.plan.storage.database.sql.tables.UserInfoTable;
import com.djrapitops.plan.storage.database.transactions.ExecStatement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import static com.djrapitops.plan.storage.database.sql.building.Sql.FROM;
/**
* Make sure hostname can be null.
*
* @author AuroraLS3
*/
public class UserInfoHostnameAllowNullPatch extends Patch {
private final String tempTableName = "temp_user_info_join_address_patching";
private final String tableName = UserInfoTable.TABLE_NAME;
@Override
public boolean hasBeenApplied() {
return hasColumn(tableName, UserInfoTable.JOIN_ADDRESS)
&& !hasColumn(tableName, "hostname")
&& !hasTable(tempTableName);
}
@Override
protected void applyPatch() {
tempOldTable();
execute(UserInfoTable.createTableSQL(dbType));
execute(new ExecStatement("INSERT INTO " + tableName + " (" +
UserInfoTable.ID + ',' +
UserInfoTable.USER_UUID + ',' +
UserInfoTable.SERVER_UUID + ',' +
UserInfoTable.REGISTERED + ',' +
UserInfoTable.OP + ',' +
UserInfoTable.BANNED + ',' +
UserInfoTable.JOIN_ADDRESS +
") SELECT " +
UserInfoTable.ID + ',' +
UserInfoTable.USER_UUID + ',' +
UserInfoTable.SERVER_UUID + ',' +
UserInfoTable.REGISTERED + ',' +
UserInfoTable.OP + ',' +
UserInfoTable.BANNED + ',' +
"?" +
FROM + tempTableName
) {
@Override
public void prepare(PreparedStatement statement) throws SQLException {
statement.setString(1, null);
}
});
dropTable(tempTableName);
}
private void tempOldTable() {
if (!hasTable(tempTableName)) {
renameTable(tableName, tempTableName);
}
}
}

View File

@ -28,12 +28,12 @@ public class UserInfoHostnamePatch extends Patch {
@Override
public boolean hasBeenApplied() {
return hasColumn(UserInfoTable.TABLE_NAME, UserInfoTable.HOSTNAME);
return hasColumn(UserInfoTable.TABLE_NAME, UserInfoTable.JOIN_ADDRESS);
}
@Override
protected void applyPatch() {
addColumn(UserInfoTable.TABLE_NAME, UserInfoTable.HOSTNAME + ' '
+ Sql.varchar(255) + " NOT NULL DEFAULT 'Unknown'");
addColumn(UserInfoTable.TABLE_NAME, UserInfoTable.JOIN_ADDRESS + ' '
+ Sql.varchar(255));
}
}

View File

@ -418,7 +418,7 @@ function serverPie(id, serverSeries) {
}));
}
function hostnamePie(id, hostnameTotals) {
function joinAddressPie(id, joinAddresses) {
graphs.push(Highcharts.chart(id, {
chart: {
plotBackgroundColor: null,
@ -442,7 +442,7 @@ function hostnamePie(id, hostnameTotals) {
return '<b>' + this.point.name + ':</b> ' + this.y + ' (' + this.percentage.toFixed(2) + '%)';
}
},
series: [hostnameTotals]
series: [joinAddresses]
}));
}

View File

@ -417,16 +417,16 @@ function loadGeolocationGraph(json, error) {
}
}
function loadHostnamePie(json, error) {
function loadJoinAddressPie(json, error) {
if (json) {
const hostnamePieSeries = {
const series = {
name: 'Used IP Addresses',
colorByPoint: true,
colors: json.hostname_pie_colors,
data: json.hostname_pie_slices
colors: json.colors,
data: json.slices
};
hostnamePie('hostnamePie', hostnamePieSeries);
joinAddressPie('joinAddressPie', series);
} else if (error) {
document.getElementById('hostnamePie').innerText = `Failed to load graph data: ${error}`;
document.getElementById('joinAddressPie').innerText = `Failed to load graph data: ${error}`;
}
}

View File

@ -587,16 +587,16 @@ function loadPunchCard(json, error) {
}
}
function loadHostnamePie(json, error) {
function loadJoinAddressPie(json, error) {
if (json) {
const hostnamePieSeries = {
const joinAddressPieSeries = {
name: 'Used IP Addresses',
colorByPoint: true,
colors: json.hostname_pie_colors,
data: json.hostname_pie_slices
colors: json.colors,
data: json.slices
};
hostnamePie('hostnamePie', hostnamePieSeries);
joinAddressPie('joinAddressPie', joinAddressPieSeries);
} else if (error) {
document.getElementById('hostnamePie').innerText = `Failed to load graph data: ${error}`;
document.getElementById('joinAddressPie').innerText = `Failed to load graph data: ${error}`;
}
}

View File

@ -615,11 +615,11 @@
<div class="card shadow mb-4">
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold col-black">
<i class="fa fa-fw fa-users col-amber"></i>
Used hostnames
<i class="fa fa-fw fa-location-arrow col-amber"></i>
Join Addresses
</h6>
</div>
<div class="chart-area" id="hostnamePie"></div>
<div class="chart-area" id="joinAddressPie"></div>
</div>
</div>
</div>
@ -917,7 +917,7 @@
refreshingJsonRequest("./v1/graph?type=uniqueAndNew", loadUniqueAndNewGraph, 'network-overview');
refreshingJsonRequest("./v1/graph?type=hourlyUniqueAndNew", loadHourlyUniqueAndNewGraph, 'network-overview');
refreshingJsonRequest("./v1/graph?type=serverPie", loadServerPie, 'sessions-overview');
refreshingJsonRequest("./v1/graph?type=hostnamePie", loadHostnamePie, 'playerbase-overview');
refreshingJsonRequest("./v1/graph?type=joinAddressPie", loadJoinAddressPie, 'playerbase-overview');
refreshingJsonRequest("./v1/graph?type=activity", loadActivityGraphs, 'playerbase-overview');
refreshingJsonRequest("./v1/graph?type=geolocation", loadGeolocationGraph, 'geolocations');

View File

@ -764,11 +764,11 @@
<div class="card shadow mb-4">
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold col-black">
<i class="fa fa-fw fa-users col-amber"></i>
Used hostnames
<i class="fa fa-fw fa-location-arrow col-amber"></i>
Join Addresses
</h6>
</div>
<div class="chart-area" id="hostnamePie"></div>
<div class="chart-area" id="joinAddressPie"></div>
</div>
</div>
</div>
@ -1398,7 +1398,7 @@
refreshingJsonRequest("../v1/graph?type=aggregatedPing&server=${serverUUID}", loadPingGraph, 'performance');
refreshingJsonRequest("../v1/graph?type=worldPie&server=${serverUUID}", loadWorldPie, 'sessions-overview');
refreshingJsonRequest("../v1/graph?type=activity&server=${serverUUID}", loadActivityGraph, 'playerbase-overview');
refreshingJsonRequest("../v1/graph?type=hostnamePie", loadHostnamePie, 'playerbase-overview');
refreshingJsonRequest("../v1/graph?type=joinAddressPie", loadJoinAddressPie, 'playerbase-overview');
refreshingJsonRequest("../v1/graph?type=geolocation&server=${serverUUID}", loadGeolocationGraph, 'geolocations');
refreshingJsonRequest("../v1/graph?type=uniqueAndNew&server=${serverUUID}", loadUniqueAndNewGraph, 'online-activity-overview');
refreshingJsonRequest("../v1/graph?type=hourlyUniqueAndNew&server=${serverUUID}", loadHourlyUniqueAndNewGraph, 'online-activity-overview');

View File

@ -66,7 +66,7 @@ public interface DatabaseTest extends DatabaseTestPreparer {
default void saveUserOne() {
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, RandomData::randomTime,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
db().executeTransaction(new KickStoreTransaction(playerUUID));
}
@ -93,7 +93,7 @@ public interface DatabaseTest extends DatabaseTestPreparer {
saveUserTwo();
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, RandomData::randomTime,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
saveTwoWorlds();
FinishedSession session = RandomData.randomSession(serverUUID(), worlds, playerUUID, player2UUID);
@ -271,7 +271,7 @@ public interface DatabaseTest extends DatabaseTestPreparer {
default void registerDateIsMinimized() {
executeTransactions(
new PlayerServerRegisterTransaction(playerUUID, () -> 1000,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME)
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME)
, new Transaction() {
@Override
protected void performOperations() {
@ -300,9 +300,9 @@ public interface DatabaseTest extends DatabaseTestPreparer {
db().executeTransaction(new WorldNameStoreTransaction(serverUUID(), worlds[0]));
db().executeTransaction(new WorldNameStoreTransaction(serverUUID(), worlds[1]));
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, RandomData::randomTime,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
db().executeTransaction(new PlayerServerRegisterTransaction(player2UUID, RandomData::randomTime,
TestConstants.PLAYER_TWO_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_TWO_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
db().executeTransaction(new SessionEndTransaction(RandomData.randomSession(serverUUID(), worlds, playerUUID, player2UUID)));
List<TablePlayer> result = db().query(new ServerTablePlayersQuery(serverUUID(), System.currentTimeMillis(), 10L, 1));
@ -315,9 +315,9 @@ public interface DatabaseTest extends DatabaseTestPreparer {
db().executeTransaction(new WorldNameStoreTransaction(serverUUID(), worlds[0]));
db().executeTransaction(new WorldNameStoreTransaction(serverUUID(), worlds[1]));
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, RandomData::randomTime,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
db().executeTransaction(new PlayerServerRegisterTransaction(player2UUID, RandomData::randomTime,
TestConstants.PLAYER_TWO_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_TWO_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
db().executeTransaction(new SessionEndTransaction(RandomData.randomSession(serverUUID(), worlds, playerUUID, player2UUID)));
List<TablePlayer> result = db().query(new NetworkTablePlayersQuery(System.currentTimeMillis(), 10L, 1));

View File

@ -51,9 +51,9 @@ public interface ActivityIndexQueriesTest extends DatabaseTestPreparer {
default void storeSessions(Predicate<FinishedSession> save) {
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, RandomData::randomTime,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
db().executeTransaction(new PlayerServerRegisterTransaction(player2UUID, RandomData::randomTime,
TestConstants.PLAYER_TWO_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_TWO_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
for (String world : worlds) {
db().executeTransaction(new WorldNameStoreTransaction(serverUUID(), world));
}

View File

@ -48,9 +48,9 @@ public interface DatabaseBackupTest extends DatabaseTestPreparer {
db().executeTransaction(new WorldNameStoreTransaction(serverUUID(), worlds[0]));
db().executeTransaction(new WorldNameStoreTransaction(serverUUID(), worlds[1]));
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, RandomData::randomTime,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
db().executeTransaction(new PlayerServerRegisterTransaction(player2UUID, RandomData::randomTime,
TestConstants.PLAYER_TWO_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_TWO_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
FinishedSession session = RandomData.randomSession(serverUUID(), worlds, playerUUID, player2UUID);
execute(DataStoreQueries.storeSession(session));

View File

@ -41,7 +41,7 @@ public interface GeolocationQueriesTest extends DatabaseTestPreparer {
@Test
default void geoInformationIsStored() {
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, RandomData::randomTime,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
List<GeoInfo> expected = RandomData.randomGeoInfo();
for (GeoInfo geoInfo : expected) {
@ -104,7 +104,7 @@ public interface GeolocationQueriesTest extends DatabaseTestPreparer {
Database db = db();
for (UUID uuid : uuids) {
db.executeTransaction(new PlayerServerRegisterTransaction(uuid, () -> 0L, "", serverUUID(),
TestConstants.PLAYER_HOSTNAME));
TestConstants.GET_PLAYER_HOSTNAME));
}
save(firstUuid, new GeoInfo("Norway", 0));

View File

@ -38,7 +38,7 @@ public interface NicknameQueriesTest extends DatabaseTestPreparer {
@Test
default void allNicknamesAreSaved() {
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, RandomData::randomTime,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
List<Nickname> saved = RandomData.randomNicknames(serverUUID());
for (Nickname nickname : saved) {

View File

@ -78,9 +78,9 @@ public interface SessionQueriesTest extends DatabaseTestPreparer {
db().executeTransaction(new WorldNameStoreTransaction(serverUUID(), worlds[0]));
db().executeTransaction(new WorldNameStoreTransaction(serverUUID(), worlds[1]));
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, RandomData::randomTime,
TestConstants.PLAYER_ONE_NAME, serverUUID(),TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
db().executeTransaction(new PlayerServerRegisterTransaction(player2UUID, RandomData::randomTime,
TestConstants.PLAYER_TWO_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_TWO_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
}
@Test

View File

@ -42,10 +42,33 @@ public interface UserInfoQueriesTest extends DatabaseTestPreparer {
@Test
default void userInfoTableStoresCorrectUserInformation() {
assertFalse(db().query(BaseUserQueries.fetchBaseUserOfPlayer(playerUUID)).isPresent());
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, () -> TestConstants.REGISTER_TIME, TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, () -> TestConstants.REGISTER_TIME, TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
List<UserInfo> userInfo = db().query(UserInfoQueries.fetchUserInformationOfUser(playerUUID));
List<UserInfo> expected = Collections.singletonList(new UserInfo(playerUUID, serverUUID(), TestConstants.REGISTER_TIME, false, TestConstants.PLAYER_HOSTNAME.get(), false));
List<UserInfo> expected = Collections.singletonList(new UserInfo(playerUUID, serverUUID(), TestConstants.REGISTER_TIME, false, TestConstants.GET_PLAYER_HOSTNAME.get(), false));
assertEquals(expected, userInfo);
}
@Test
default void joinAddressCanBeNull() {
assertFalse(db().query(BaseUserQueries.fetchBaseUserOfPlayer(playerUUID)).isPresent());
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, () -> TestConstants.REGISTER_TIME, TestConstants.PLAYER_ONE_NAME, serverUUID(), () -> null));
List<UserInfo> userInfo = db().query(UserInfoQueries.fetchUserInformationOfUser(playerUUID));
List<UserInfo> expected = Collections.singletonList(new UserInfo(playerUUID, serverUUID(), TestConstants.REGISTER_TIME, false, null, false));
assertEquals(expected, userInfo);
}
@Test
default void joinAddressIsUpdatedUponSecondLogin() {
assertFalse(db().query(BaseUserQueries.fetchBaseUserOfPlayer(playerUUID)).isPresent());
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, () -> TestConstants.REGISTER_TIME, TestConstants.PLAYER_ONE_NAME, serverUUID(), () -> null));
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, () -> TestConstants.REGISTER_TIME, TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
List<UserInfo> userInfo = db().query(UserInfoQueries.fetchUserInformationOfUser(playerUUID));
List<UserInfo> expected = Collections.singletonList(new UserInfo(playerUUID, serverUUID(), TestConstants.REGISTER_TIME, false, TestConstants.GET_PLAYER_HOSTNAME.get(), false));
assertEquals(expected, userInfo);
}
@ -53,12 +76,12 @@ public interface UserInfoQueriesTest extends DatabaseTestPreparer {
@Test
default void userInfoTableUpdatesBanStatus() {
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, () -> TestConstants.REGISTER_TIME,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
db().executeTransaction(new BanStatusTransaction(playerUUID, () -> true));
List<UserInfo> userInfo = db().query(UserInfoQueries.fetchUserInformationOfUser(playerUUID));
List<UserInfo> expected = Collections.singletonList(new UserInfo(playerUUID, serverUUID(), TestConstants.REGISTER_TIME, false, TestConstants.PLAYER_HOSTNAME.get(), true));
List<UserInfo> expected = Collections.singletonList(new UserInfo(playerUUID, serverUUID(), TestConstants.REGISTER_TIME, false, TestConstants.GET_PLAYER_HOSTNAME.get(), true));
assertEquals(expected, userInfo);
}
@ -66,12 +89,12 @@ public interface UserInfoQueriesTest extends DatabaseTestPreparer {
@Test
default void userInfoTableUpdatesOperatorStatus() {
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, () -> TestConstants.REGISTER_TIME,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
db().executeTransaction(new OperatorStatusTransaction(playerUUID, true));
List<UserInfo> userInfo = db().query(UserInfoQueries.fetchUserInformationOfUser(playerUUID));
List<UserInfo> expected = Collections.singletonList(new UserInfo(playerUUID, serverUUID(), TestConstants.REGISTER_TIME, true, TestConstants.PLAYER_HOSTNAME.get(), false));
List<UserInfo> expected = Collections.singletonList(new UserInfo(playerUUID, serverUUID(), TestConstants.REGISTER_TIME, true, TestConstants.GET_PLAYER_HOSTNAME.get(), false));
assertEquals(expected, userInfo);
}
@ -79,7 +102,7 @@ public interface UserInfoQueriesTest extends DatabaseTestPreparer {
@Test
default void playerNameIsUpdatedWhenPlayerLogsIn() {
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, () -> TestConstants.REGISTER_TIME,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
OptionalAssert.equals(playerUUID, db().query(UserIdentifierQueries.fetchPlayerUUIDOf(TestConstants.PLAYER_ONE_NAME)));
@ -153,7 +176,7 @@ public interface UserInfoQueriesTest extends DatabaseTestPreparer {
assertFalse(db().query(PlayerFetchQueries.isPlayerRegistered(playerUUID)));
assertFalse(db().query(PlayerFetchQueries.isPlayerRegisteredOnServer(playerUUID, serverUUID())));
db().executeTransaction(new PlayerServerRegisterTransaction(playerUUID, () -> TestConstants.REGISTER_TIME,
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.PLAYER_HOSTNAME));
TestConstants.PLAYER_ONE_NAME, serverUUID(), TestConstants.GET_PLAYER_HOSTNAME));
assertTrue(db().query(PlayerFetchQueries.isPlayerRegistered(playerUUID)));
assertTrue(db().query(PlayerFetchQueries.isPlayerRegisteredOnServer(playerUUID, serverUUID())));
}
@ -180,11 +203,11 @@ public interface UserInfoQueriesTest extends DatabaseTestPreparer {
@Override
protected void performOperations() {
execute(DataStoreQueries.registerUserInfo(playerUUID, 0L,
serverUUID(), TestConstants.PLAYER_HOSTNAME.get()));
serverUUID(), TestConstants.GET_PLAYER_HOSTNAME.get()));
execute(DataStoreQueries.registerUserInfo(playerUUID, 0L,
serverUUID(), TestConstants.PLAYER_HOSTNAME.get()));
serverUUID(), TestConstants.GET_PLAYER_HOSTNAME.get()));
execute(DataStoreQueries.registerUserInfo(player2UUID, 0L,
serverUUID(), TestConstants.PLAYER_HOSTNAME.get()));
serverUUID(), TestConstants.GET_PLAYER_HOSTNAME.get()));
}
}).get();
@ -192,13 +215,13 @@ public interface UserInfoQueriesTest extends DatabaseTestPreparer {
List<UserInfo> found = db().query(UserInfoQueries.fetchUserInformationOfUser(playerUUID));
assertEquals(
Collections.singletonList(new UserInfo(playerUUID, serverUUID(), 0, false, TestConstants.PLAYER_HOSTNAME.get(), false)),
Collections.singletonList(new UserInfo(playerUUID, serverUUID(), 0, false, TestConstants.GET_PLAYER_HOSTNAME.get(), false)),
found
);
List<UserInfo> found2 = db().query(UserInfoQueries.fetchUserInformationOfUser(player2UUID));
assertEquals(
Collections.singletonList(new UserInfo(player2UUID, serverUUID(), 0, false, TestConstants.PLAYER_HOSTNAME.get(), false)),
Collections.singletonList(new UserInfo(player2UUID, serverUUID(), 0, false, TestConstants.GET_PLAYER_HOSTNAME.get(), false)),
found2
);
}
@ -238,4 +261,22 @@ public interface UserInfoQueriesTest extends DatabaseTestPreparer {
default void noMinimumRegisterDateIsFetchedWithNoData() {
assertFalse(db().query(BaseUserQueries.minimumRegisterDate()).isPresent());
}
@Test
default void joinAddressQueryHasNoNullValues() {
joinAddressCanBeNull();
Map<String, Integer> expected = Collections.singletonMap("Unknown", 1);
Map<String, Integer> result = db().query(UserInfoQueries.joinAddresses());
assertEquals(expected, result);
}
@Test
default void serverJoinAddressQueryHasNoNullValues() {
joinAddressCanBeNull();
Map<String, Integer> expected = Collections.singletonMap("Unknown", 1);
Map<String, Integer> result = db().query(UserInfoQueries.joinAddresses(serverUUID()));
assertEquals(expected, result);
}
}

View File

@ -45,7 +45,7 @@ public class TestConstants {
public static final String PLAYER_TWO_NAME = "Test_Player_two";
public static final String PLAYER_THREE_NAME = RandomData.randomString(16);
public static final Supplier<String> PLAYER_HOSTNAME = () -> "play.example.com";
public static final Supplier<String> GET_PLAYER_HOSTNAME = () -> "play.example.com";
public static final String WORLD_ONE_NAME = "World One";
public static final String[] WORLDS = new String[]{WORLD_ONE_NAME};

View File

@ -117,9 +117,9 @@ public class TestData {
@Override
protected void performOperations() {
executeOther(new PlayerServerRegisterTransaction(playerUUID, () -> playerFirstJoin,
playerName, serverUUID, TestConstants.PLAYER_HOSTNAME));
playerName, serverUUID, TestConstants.GET_PLAYER_HOSTNAME));
executeOther(new PlayerServerRegisterTransaction(playerUUID, () -> playerSecondJoin,
playerName, server2UUID, TestConstants.PLAYER_HOSTNAME));
playerName, server2UUID, TestConstants.GET_PLAYER_HOSTNAME));
for (GeoInfo geoInfo : playerGeoInfo) {
executeOther(new GeoInfoStoreTransaction(playerUUID, geoInfo));
@ -140,9 +140,9 @@ public class TestData {
@Override
protected void performOperations() {
executeOther(new PlayerServerRegisterTransaction(player2UUID, () -> playerFirstJoin,
player2Name, serverUUID, TestConstants.PLAYER_HOSTNAME));
player2Name, serverUUID, TestConstants.GET_PLAYER_HOSTNAME));
executeOther(new PlayerServerRegisterTransaction(player2UUID, () -> playerSecondJoin,
player2Name, server2UUID, TestConstants.PLAYER_HOSTNAME));
player2Name, server2UUID, TestConstants.GET_PLAYER_HOSTNAME));
for (GeoInfo geoInfo : playerGeoInfo) {
executeOther(new GeoInfoStoreTransaction(player2UUID, geoInfo));

View File

@ -161,7 +161,7 @@ public class PlayerOnlineListener implements Listener {
database.executeTransaction(new WorldNameStoreTransaction(serverUUID, world));
InetAddress address = player.getSocketAddress().getAddress();
Supplier<String> getHostName = () -> player.getSocketAddress().getHostName();
Supplier<String> getHostName = () -> null;
String playerName = player.getName();
String displayName = player.getDisplayName();