removed IllegalStateException throws from method signatures

changed Exception to IllegalArgumentException in the renamed API method
RawData: optimized placeholder String creation method
DataCacheClearQueue: fixed Reuse of method parameter
DataCacheGetQueue: removed nested try block
DeathEventListener: better catch

Removed duplicate user removal code with introduction of UserIDTable

Removed some debug messages that are not useful
This commit is contained in:
Rsl1122 2017-08-16 11:54:29 +03:00
parent d3a7f5adae
commit 26ab4e94d2
18 changed files with 118 additions and 163 deletions

View File

@ -86,7 +86,7 @@ public class Plan extends BukkitPlugin<Plan> {
* Plan and the instance is null.
* @throws NoClassDefFoundError If Plan is not installed.
*/
public static API getPlanAPI() throws IllegalStateException, NoClassDefFoundError {
public static API getPlanAPI() throws NoClassDefFoundError {
Plan instance = getInstance();
if (instance == null) {
throw new IllegalStateException("Plugin not enabled properly, Singleton instance is null.");
@ -323,7 +323,7 @@ public class Plan extends BukkitPlugin<Plan> {
return Check.errorIfFalse(db.init(), Locale.get(Msg.ENABLE_DB_FAIL_DISABLE_INFO).toString());
}
private void startAnalysisRefreshTask(int everyXMinutes) throws IllegalStateException {
private void startAnalysisRefreshTask(int everyXMinutes) {
Benchmark.start("Schedule PeriodicAnalysisTask");
if (everyXMinutes <= 0) {
return;
@ -340,7 +340,7 @@ public class Plan extends BukkitPlugin<Plan> {
Benchmark.stop("Schedule PeriodicAnalysisTask");
}
private void startBootAnalysisTask() throws IllegalStateException {
private void startBootAnalysisTask() {
Benchmark.start("Schedule boot analysis task");
String bootAnalysisMsg = Locale.get(Msg.ENABLE_BOOT_ANALYSIS_INFO).toString();
String bootAnalysisRunMsg = Locale.get(Msg.ENABLE_BOOT_ANALYSIS_RUN_INFO).toString();

View File

@ -264,12 +264,12 @@ public class API {
*
* @param playerName Player's name
* @return UUID of the Player
* @throws Exception if player's name is not registered at Mojang
* @throws IllegalArgumentException if player's name is not registered at Mojang
*/
public UUID playerNameToUUID(String playerName) throws Exception {
public UUID playerNameToUUID(String playerName) {
UUID uuid = UUIDUtility.getUUIDOf(playerName);
if (uuid == null) {
throw new Exception("UUID did not get a match");
throw new IllegalArgumentException("UUID did not get a match");
}
return uuid;
}

View File

@ -59,4 +59,4 @@ public class ListCommand extends SubCommand {
}
sender.sendMessage(Locale.get(Msg.CMD_CONSTANT_FOOTER).toString());
}
}
}

View File

@ -24,13 +24,13 @@ import java.util.UUID;
*/
public class KillPart extends RawData {
private final PlayerCountPart playerCount;
private final PlayerCountPart playerCountPart;
private final Map<UUID, List<KillData>> playerKills;
private long mobKills;
private long deaths;
public KillPart(PlayerCountPart playerCount) {
this.playerCount = playerCount;
public KillPart(PlayerCountPart playerCountPart) {
this.playerCountPart = playerCountPart;
playerKills = new HashMap<>();
mobKills = 0;
deaths = 0;
@ -42,7 +42,7 @@ public class KillPart extends RawData {
addValue("mobkills", mobKills);
int playerKillAmount = getAllPlayerKills().size();
addValue("playerkills", playerKillAmount);
int playerCount = this.playerCount.getPlayerCount();
int playerCount = playerCountPart.getPlayerCount();
addValue("avgdeaths", MathUtils.averageLong(deaths, playerCount));
addValue("avgmobkills", MathUtils.averageLong(mobKills, playerCount));
addValue("avgplayerkills", MathUtils.averageLong(playerKillAmount, playerCount));

View File

@ -77,13 +77,20 @@ public abstract class RawData {
}
private String addPlaceholderSigns(String placeholder) {
StringBuilder newPlaceholder = new StringBuilder();
if (placeholder.charAt(0) != '%') {
placeholder = "%" + placeholder;
newPlaceholder.append("%");
}
if (placeholder.charAt(placeholder.length() - 1) != '%') {
placeholder += "%";
newPlaceholder.append(placeholder);
int lastIndex = placeholder.length() - 1;
if (placeholder.charAt(lastIndex) != '%') {
newPlaceholder.append("%");
}
return placeholder;
return newPlaceholder.toString();
}
/**

View File

@ -3,7 +3,6 @@ package main.java.com.djrapitops.plan.data.cache;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.utilities.Benchmark;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@ -45,18 +44,14 @@ public class GeolocationCacheHandler {
* @see #getUncachedCountry(String)
*/
public static String getCountry(String ipAddress) {
Log.debug("Started country retrieval from IP Address " + ipAddress);
String country = getCachedCountry(ipAddress);
if (country != null) {
Log.debug("Got cached country from IP Address " + ipAddress + ": " + country);
return country;
} else {
country = getUncachedCountry(ipAddress);
geolocationCache.put(ipAddress, country);
Log.debug("Got uncached country from IP Address " + ipAddress + ": " + country);
return country;
}
}
@ -75,16 +70,16 @@ public class GeolocationCacheHandler {
* @see #getCountry(String)
*/
public static String getUncachedCountry(String ipAddress) {
Benchmark.start("getUncachedCountry");
URL url;
String urlString = "http://freegeoip.net/csv/" + ipAddress;
String unknownString = "Not Known";
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
Log.error("The URL \"" + urlString + "\" couldn't be converted to URL: " + e.getCause()); //Shouldn't ever happen
return "Not Known";
return unknownString;
}
try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
@ -94,11 +89,9 @@ public class GeolocationCacheHandler {
String[] results = resultLine.split(",");
String result = results[2];
return result.isEmpty() ? "Not Known" : result;
return result.isEmpty() ? unknownString : result;
} catch (Exception exc) {
return "Not Known";
} finally {
Benchmark.stop("getUncachedCountry");
return unknownString;
}
}

View File

@ -1,5 +1,6 @@
package main.java.com.djrapitops.plan.data.cache.queue;
import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.cache.DataCacheHandler;
@ -47,12 +48,11 @@ public class DataCacheClearQueue extends Queue<UUID> {
* @param uuids UUIDs of the UserData object (Players' UUIDs)
*/
public void scheduleForClear(Collection<UUID> uuids) {
if (uuids.isEmpty()) {
if (Verify.isEmpty(uuids)) {
return;
}
uuids = uuids.stream().filter(Objects::nonNull).collect(Collectors.toList());
try {
queue.addAll(uuids);
queue.addAll(uuids.stream().filter(Objects::nonNull).collect(Collectors.toList()));
} catch (IllegalStateException e) {
Log.error(Locale.get(Msg.RUN_WARN_QUEUE_SIZE).parse("Clear Queue", Settings.PROCESS_CLEAR_LIMIT.getNumber()));
}

View File

@ -1,5 +1,6 @@
package main.java.com.djrapitops.plan.data.cache.queue;
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.Settings;
@ -8,7 +9,6 @@ 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.sql.SQLException;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
@ -75,21 +75,12 @@ class GetConsumer extends Consumer<Map<UUID, List<DBCallableProcessor>>> {
try {
for (Map.Entry<UUID, List<DBCallableProcessor>> entrySet : processors.entrySet()) {
UUID uuid = entrySet.getKey();
if (uuid == null) {
List<DBCallableProcessor> processorsList = entrySet.getValue();
if (uuid == null || Verify.isEmpty(processorsList)) {
continue;
}
List<DBCallableProcessor> processorsList = entrySet.getValue();
if (processorsList != null) {
Log.debug("Database", uuid + ": Get, For:" + processorsList.size());
try {
db.giveUserDataToProcessors(uuid, processorsList);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
}
Log.debug("Database", uuid + ": Get, For:" + processorsList.size());
db.giveUserDataToProcessors(uuid, processorsList);
}
} catch (Exception ex) {
Log.toLog(this.getClass().getName(), ex);

View File

@ -10,7 +10,6 @@ import main.java.com.djrapitops.plan.locale.Locale;
import main.java.com.djrapitops.plan.locale.Msg;
import java.sql.SQLException;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
@ -48,19 +47,6 @@ public class DataCacheSaveQueue extends Queue<UserData> {
}
}
/**
* Schedule multiple UserData objects to be saved to the database.
*
* @param data Collection of UserData objects.
*/
public void scheduleForSave(Collection<UserData> data) {
try {
queue.addAll(data);
} catch (IllegalStateException e) {
Log.error(Locale.get(Msg.RUN_WARN_QUEUE_SIZE).parse("Save Queue", Settings.PROCESS_SAVE_LIMIT.getNumber()));
}
}
/**
* Schedule UserData object for a new player to be saved to the database.
*
@ -68,11 +54,7 @@ public class DataCacheSaveQueue extends Queue<UserData> {
*/
public void scheduleNewPlayer(UserData data) {
Log.debug(data.getUuid() + ": Scheduling new Player");
try {
queue.add(data);
} catch (IllegalStateException e) {
Log.error(Locale.get(Msg.RUN_WARN_QUEUE_SIZE).parse("Save Queue", Settings.PROCESS_SAVE_LIMIT.getNumber()));
}
scheduleForSave(data);
}
/**

View File

@ -64,7 +64,7 @@ public class PlanDeathEventListener implements Listener {
} catch (NoSuchMethodError e) {
try {
itemInHand = killer.getInventory().getItemInHand().getType(); // Support for non dual wielding versions.
} catch (Error e2) {
} catch (Exception | NoSuchMethodError | NoSuchFieldError e2) {
itemInHand = Material.AIR;
}
}

View File

@ -89,8 +89,9 @@ public class TPSCountTimer extends AbsRunnable {
} else {
entityCount = getEntityCount();
diff -= TimeAmount.MILLISECOND.ns() * 40L; // 40ms removed because the run appears to take 40-50ms, screwing the tps.
return getTPS(diff, now, averageCPUUsage, usedMemory, entityCount, loadedChunks, playersOnline);
// 40ms removed because the run appears to take 40-50ms, screwing the tps.
long fourtyMsAsNs = TimeAmount.MILLISECOND.ns() * 40L;
return getTPS(diff - fourtyMsAsNs, now, averageCPUUsage, usedMemory, entityCount, loadedChunks, playersOnline);
}
}
@ -104,17 +105,18 @@ public class TPSCountTimer extends AbsRunnable {
* @return the TPS
*/
private TPS getTPS(long diff, long now, double cpuUsage, long usedMemory, int entityCount, int chunksLoaded, int playersOnline) {
if (diff < TimeAmount.SECOND.ns()) { // No tick count above 20
diff = TimeAmount.SECOND.ns();
long difference = diff;
if (difference < TimeAmount.SECOND.ns()) { // No tick count above 20
difference = TimeAmount.SECOND.ns();
}
long twentySeconds = 20L * TimeAmount.SECOND.ns();
while (diff > twentySeconds) {
while (difference > twentySeconds) {
history.add(new TPS(now, 0, playersOnline, cpuUsage, usedMemory, entityCount, chunksLoaded));
diff -= twentySeconds;
difference -= twentySeconds;
}
double tpsN = twentySeconds * 1.0 / diff;
double tpsN = twentySeconds * 1.0 / difference;
return new TPS(now, tpsN, playersOnline, cpuUsage, usedMemory, entityCount, chunksLoaded);
}

View File

@ -46,8 +46,9 @@ public abstract class TimeKeeper {
/**
* Sets a specific time for a state.
*
* @param state State to set
* @param time Time in ms the state has been active for
* @param time Time in ms the state has been active for
* @throws IllegalArgumentException If given state is null
*/
public void setTime(String state, long time) {
@ -71,14 +72,10 @@ public abstract class TimeKeeper {
*
* @param newState New State seen in.
* @param playTime Current Playtime.
* @throws IllegalArgumentException If new state is null.
* @throws IllegalStateException If lastStateChange time is higher than playtime.
* @throws IllegalArgumentException If newState is null.
*/
public void changeState(String newState, long playTime) {
Verify.nullCheck(newState);
// if (playTime < lastStateChange) {
// throw new IllegalStateException("Given Playtime is lower than last status change time: " + playTime + " / " + lastStateChange);
// }
if (state == null) {
state = newState;
}
@ -146,9 +143,9 @@ public abstract class TimeKeeper {
TimeKeeper that = (TimeKeeper) o;
return lastStateChange == that.lastStateChange &&
times != null ? times.equals(that.times) : that.times == null
&& state != null ? state.equals(that.state) : that.state == null;
return lastStateChange == that.lastStateChange
&& (times != null ? times.equals(that.times) : that.times == null)
&& (state != null ? state.equals(that.state) : that.state == null);
}
@Override

View File

@ -15,14 +15,19 @@ import java.util.*;
/**
* @author Rsl1122
*/
public class GMTimesTable extends Table {
public class GMTimesTable extends UserIDTable {
private final String columnUserID;
private final String columnSurvivalTime;
private final String columnCreativeTime;
private final String columnAdventureTime;
private final String columnSpectatorTime;
private static final String SURVIVAL = "SURVIVAL";
private static final String CREATIVE = "CREATIVE";
private static final String ADVENTURE = "ADVENTURE";
private static final String SPECTATOR = "SPECTATOR";
/**
* @param db
* @param usingMySQL
@ -30,14 +35,14 @@ public class GMTimesTable extends Table {
public GMTimesTable(SQLDB db, boolean usingMySQL) {
super("plan_gamemodetimes", db, usingMySQL);
columnUserID = "user_id";
columnSurvivalTime = "survival";
columnCreativeTime = "creative";
columnAdventureTime = "adventure";
columnSpectatorTime = "spectator";
columnSurvivalTime = "SURVIVAL";
columnCreativeTime = "CREATIVE";
columnAdventureTime = "ADVENTURE";
columnSpectatorTime = "SPECTATOR";
}
public static String[] getGMKeyArray() {
return new String[]{"SURVIVAL", "CREATIVE", "ADVENTURE", "SPECTATOR"};
return new String[]{SURVIVAL, CREATIVE, ADVENTURE, SPECTATOR};
}
/**
@ -68,18 +73,7 @@ public class GMTimesTable extends Table {
* @return
*/
public boolean removeUserGMTimes(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 {
close(statement);
}
return super.removeDataOf(userId);
}
/**
@ -97,10 +91,10 @@ public class GMTimesTable extends Table {
HashMap<String, Long> times = new HashMap<>();
while (set.next()) {
times.put("SURVIVAL", set.getLong(columnSurvivalTime));
times.put("CREATIVE", set.getLong(columnCreativeTime));
times.put("ADVENTURE", set.getLong(columnAdventureTime));
times.put("SPECTATOR", set.getLong(columnSpectatorTime));
times.put(SURVIVAL, set.getLong(columnSurvivalTime));
times.put(CREATIVE, set.getLong(columnCreativeTime));
times.put(ADVENTURE, set.getLong(columnAdventureTime));
times.put(SPECTATOR, set.getLong(columnSpectatorTime));
}
return times;
@ -125,10 +119,10 @@ public class GMTimesTable extends Table {
continue;
}
gmTimes.put("SURVIVAL", set.getLong(columnSurvivalTime));
gmTimes.put("CREATIVE", set.getLong(columnCreativeTime));
gmTimes.put("ADVENTURE", set.getLong(columnAdventureTime));
gmTimes.put("SPECTATOR", set.getLong(columnSpectatorTime));
gmTimes.put(SURVIVAL, set.getLong(columnSurvivalTime));
gmTimes.put(CREATIVE, set.getLong(columnCreativeTime));
gmTimes.put(ADVENTURE, set.getLong(columnAdventureTime));
gmTimes.put(SPECTATOR, set.getLong(columnSpectatorTime));
times.put(id, gmTimes);
}

View File

@ -15,9 +15,8 @@ import java.util.*;
/**
* @author Rsl1122
*/
public class IPsTable extends Table {
public class IPsTable extends UserIDTable {
private final String columnUserID;
private final String columnIP;
/**
@ -55,18 +54,7 @@ public class IPsTable extends Table {
* @return if the IPs were removed successfully
*/
public boolean removeUserIPs(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 {
close(statement);
}
return super.removeDataOf(userId);
}
/**

View File

@ -13,9 +13,8 @@ import java.util.*;
/**
* @author Rsl1122
*/
public class NicknamesTable extends Table {
public class NicknamesTable extends UserIDTable {
private final String columnUserID;
private final String columnNick;
private final String columnCurrent;
@ -64,18 +63,7 @@ public class NicknamesTable extends Table {
* @return if the removal was successful
*/
public boolean removeUserNicknames(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 {
close(statement);
}
return super.removeDataOf(userId);
}
/**

View File

@ -14,9 +14,8 @@ import java.util.*;
/**
* @author Rsl1122
*/
public class SessionsTable extends Table {
public class SessionsTable extends UserIDTable {
private final String columnUserID;
private final String columnSessionStart;
private final String columnSessionEnd;
@ -82,18 +81,7 @@ public class SessionsTable extends Table {
* @return
*/
public boolean removeUserSessions(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 {
close(statement);
}
return super.removeDataOf(userId);
}
/**

View File

@ -0,0 +1,37 @@
package main.java.com.djrapitops.plan.database.tables;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.database.databases.SQLDB;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Represents a Table that uses UsersTable IDs to get their data.
*
* @author Rsl1122
* @since 3.7.0
*/
public abstract class UserIDTable extends Table {
protected String columnUserID;
public UserIDTable(String name, SQLDB db, boolean usingMySQL) {
super(name, db, usingMySQL);
}
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 {
close(statement);
}
}
}

View File

@ -17,14 +17,13 @@ import java.util.Map;
* @author Rsl1122
* @since 3.6.0 / Database version 7
*/
public class WorldTimesTable extends Table {
public class WorldTimesTable extends UserIDTable {
private final WorldTable worldTable;
private final String worldIDColumn;
private final String worldNameColumn;
private final String columnWorldId;
private final String columnUserID;
private final String columnPlaytime;
private final String selectWorldIDsql;
@ -67,18 +66,7 @@ public class WorldTimesTable extends Table {
}
public boolean removeUserWorldTimes(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 {
close(statement);
}
return super.removeDataOf(userId);
}
/**