Fixes some memory leaks by closing Scanner, FileWriter, FileOutputStreams...

Fixes some other in-depth command help
Fixes equality tests with floating point values
Adds hashCode() for UserData
Fixes some equals methods for checking if doubles are equals -> Using Double.compare(x1, x2) == 0 instead of x1 == x2
Replaces Throwable in Catch blocks with Exception to prevent catching Errors like OutOfMemoryError or InternalError.
Removes <T extends RawData> in RawData (unused)
Changes the abstract class DBCallableProcessor to an interface
Changes try to try-with-resource
Removes some parentheses
Changes some HashMap returns to Map
Changes some HashSet returns to Set
Removes unused variables
Further conversion to String.valueOf(Primitive) to save memory and CPU cycles
Changes all .values() or .keySet() calls to .entrySet() when both values are being used, that saves memory and CPU cycles
Fixes some JavaDoc comments
Corrects some Enum names to match the Java Convention Naming Scheme for them
Removes unused methods which aren't going to be used in the future
Removes unnecessary thrown Exceptions
Converts some variables to local variables
Add @Override annotation
Removed some commented-out code
Changed some method names to be more meaningful and match the Java Naming Conventions
Converts the local variable "df" in MathUtils to a global one
Changes some access-level modifiers
More little performance fixes and code cleanups
This commit is contained in:
Fuzzlemann 2017-07-29 04:42:13 +02:00
parent afe1679b68
commit d7f4168aa6
94 changed files with 777 additions and 399 deletions

View File

@ -12,6 +12,13 @@ import java.util.Collection;
*/
public class Log {
/**
* Constructor used to hide the public constructor
*/
private Log() {
throw new IllegalStateException("Utility Class");
}
/**
* Logs the message to the console as INFO.
*

View File

@ -189,8 +189,7 @@ public enum Phrase {
}
static void loadLocale(File localeFile) {
try {
Scanner localeScanner = new Scanner(localeFile, "UTF-8");
try (Scanner localeScanner = new Scanner(localeFile, "UTF-8")) {
List<String> localeRows = new ArrayList<>();
while (localeScanner.hasNextLine()) {
String line = localeScanner.nextLine();
@ -210,7 +209,7 @@ public enum Phrase {
}
}
} catch (IOException e) {
Log.error("Error at Locale Scanning: " + e.getCause());
}
}

View File

@ -45,8 +45,10 @@ import main.java.com.djrapitops.plan.utilities.metrics.BStats;
import org.bukkit.Bukkit;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@ -133,7 +135,7 @@ public class Plan extends BukkitPlugin<Plan> {
Benchmark.start("Enable: Init Database");
Log.info(Phrase.DB_INIT + "");
if (Check.isTrue_Error(initDatabase(), Phrase.DB_FAILURE_DISABLE.toString())) {
if (Check.ErrorIfFalse(initDatabase(), Phrase.DB_FAILURE_DISABLE.toString())) {
Log.info(Phrase.DB_ESTABLISHED.parse(db.getConfigName()));
} else {
disablePlugin();
@ -274,7 +276,7 @@ public class Plan extends BukkitPlugin<Plan> {
databases.add(new MySQLDB(this));
databases.add(new SQLiteDB(this));
String dbType = (Settings.DB_TYPE + "").toLowerCase().trim();
String dbType = Settings.DB_TYPE.toString().toLowerCase().trim();
for (Database database : databases) {
String databaseType = database.getConfigName().toLowerCase().trim();
@ -284,11 +286,13 @@ public class Plan extends BukkitPlugin<Plan> {
break;
}
}
if (!Verify.notNull(db)) {
Log.info(Phrase.DB_TYPE_DOES_NOT_EXIST.toString() + " " + dbType);
return false;
}
return Check.isTrue_Error(db.init(), Phrase.DB_FAILURE_DISABLE.toString());
return Check.ErrorIfFalse(db.init(), Phrase.DB_FAILURE_DISABLE.toString());
}
private void startAnalysisRefreshTask(int everyXMinutes) throws IllegalStateException {
@ -300,9 +304,7 @@ public class Plan extends BukkitPlugin<Plan> {
@Override
public void run() {
Log.debug("Running PeriodicalAnalysisTask");
if (!analysisCache.isCached()) {
analysisCache.updateCache();
} else if (MiscUtils.getTime() - analysisCache.getData().getRefreshDate() > TimeAmount.MINUTE.ms()) {
if (!analysisCache.isCached() || MiscUtils.getTime() - analysisCache.getData().getRefreshDate() > TimeAmount.MINUTE.ms()) {
analysisCache.updateCache();
}
}
@ -331,10 +333,14 @@ public class Plan extends BukkitPlugin<Plan> {
*/
public void writeNewLocaleFile() {
File genLocale = new File(getDataFolder(), "locale_EN.txt");
try {
genLocale.createNewFile();
FileWriter fw = new FileWriter(genLocale, true);
PrintWriter pw = new PrintWriter(fw);
try (
FileWriter fw = new FileWriter(genLocale, true);
PrintWriter pw = new PrintWriter(fw)
) {
if (genLocale.createNewFile()) {
Log.debug(genLocale.getAbsoluteFile() + " created");
}
for (Phrase p : Phrase.values()) {
pw.println(p.name() + " <> " + p.parse());
pw.flush();
@ -350,41 +356,76 @@ public class Plan extends BukkitPlugin<Plan> {
}
private void initLocale() {
String defaultLocale = "Default: EN";
String locale = Settings.LOCALE.toString().toUpperCase();
Benchmark.start("Enable: Initializing locale");
File localeFile = new File(getDataFolder(), "locale.txt");
boolean skipLoc = false;
String usingLocale = "";
String usingLocale;
if (localeFile.exists()) {
Phrase.loadLocale(localeFile);
Html.loadLocale(localeFile);
skipLoc = true;
usingLocale = "locale.txt";
stopInitLocale(defaultLocale);
return;
}
if (!locale.equals("DEFAULT")) {
try {
if (!skipLoc) {
URL localeURL = new URL("https://raw.githubusercontent.com/Rsl1122/Plan-PlayerAnalytics/master/Plan/localization/locale_" + locale + ".txt");
InputStream inputStream = localeURL.openStream();
OutputStream outputStream = new FileOutputStream(localeFile);
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
Phrase.loadLocale(localeFile);
Html.loadLocale(localeFile);
usingLocale = locale;
localeFile.delete();
}
} catch (FileNotFoundException ex) {
Log.error("Attempted using locale that doesn't exist.");
usingLocale = "Default: EN";
} catch (IOException e) {
if (locale.equals("DEFAULT")) {
stopInitLocale(defaultLocale);
return;
}
String urlString = "https://raw.githubusercontent.com/Rsl1122/Plan-PlayerAnalytics/master/Plan/localization/locale_" + locale + ".txt";
URL localeURL;
try {
localeURL = new URL(urlString);
} catch (MalformedURLException e) {
Log.error("Error at parsing \"" + urlString + "\" to an URL"); //Shouldn't ever happen
stopInitLocale(defaultLocale);
return;
}
try (InputStream inputStream = localeURL.openStream();
OutputStream outputStream = new FileOutputStream(localeFile)) {
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} else {
usingLocale = "Default: EN";
Phrase.loadLocale(localeFile);
Html.loadLocale(localeFile);
usingLocale = locale;
if (localeFile.delete()) {
Log.debug(localeFile.getAbsoluteFile() + " (Locale File) deleted");
}
stopInitLocale(usingLocale);
} catch (FileNotFoundException ex) {
Log.error("Attempted using locale that doesn't exist.");
stopInitLocale(defaultLocale);
} catch (IOException e) {
Log.error("Error at loading locale from GitHub, using default locale.");
stopInitLocale(defaultLocale);
}
}
/**
* Stops initializing the locale
*
* @implNote Removes clutter in the method
*
* @param usingLocale The locale that's used
*/
private void stopInitLocale(String usingLocale) {
Benchmark.stop("Enable: Initializing locale");
Log.info("Using locale: " + usingLocale);
}
@ -450,7 +491,7 @@ public class Plan extends BukkitPlugin<Plan> {
*
* @return Set containing the SqLite and MySQL objects.
*/
public HashSet<Database> getDatabases() {
public Set<Database> getDatabases() {
return databases;
}

View File

@ -14,6 +14,13 @@ import java.util.UUID;
*/
public class ConditionUtils {
/**
* Constructor used to hide the public constructor
*/
private ConditionUtils() {
throw new IllegalStateException("Utility class");
}
/**
* Check if the plugin can display the data.
*

View File

@ -4,7 +4,6 @@ import com.djrapitops.plugin.command.CommandType;
import com.djrapitops.plugin.command.TreeCommand;
import com.djrapitops.plugin.command.defaultcmds.StatusCommand;
import com.djrapitops.plugin.settings.ColorScheme;
import com.djrapitops.plugin.settings.DefaultMessages;
import main.java.com.djrapitops.plan.Permissions;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.command.commands.*;
@ -35,8 +34,6 @@ public class PlanCommand extends TreeCommand<Plan> {
private void setHelp(Plan plugin) {
ColorScheme colorScheme = plugin.getColorScheme();
String ball = DefaultMessages.BALL.toString();
String mCol = colorScheme.getMainColor();
String sCol = colorScheme.getSecondaryColor();
String tCol = colorScheme.getTertiaryColor();
@ -47,6 +44,8 @@ public class PlanCommand extends TreeCommand<Plan> {
sCol + " /plan - List subcommands",
sCol + " /plan <subcommand> ? - in depth help"
};
setInDepthHelp(help);
}
@Override

View File

@ -61,10 +61,10 @@ public class AnalyzeCommand extends SubCommand {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Phrase.ERROR_WEBSERVER_OFF_ANALYSIS.toString(), sender)) {
return true;
}
if (!Check.isTrue(analysisCache.isAnalysisEnabled(), Phrase.ERROR_ANALYSIS_DISABLED_TEMPORARILY.toString(), sender)) {
if (!analysisCache.isCached()) {
return true;
}
if (!Check.isTrue(analysisCache.isAnalysisEnabled(), Phrase.ERROR_ANALYSIS_DISABLED_TEMPORARILY.toString(), sender)
&& !analysisCache.isCached()) {
return true;
}
sender.sendMessage(Phrase.GRABBING_DATA_MESSAGE + "");

View File

@ -59,14 +59,14 @@ public class QuickAnalyzeCommand extends SubCommand {
@Override
public boolean onCommand(ISender sender, String commandLabel, String[] args) {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Phrase.ERROR_WEBSERVER_OFF_ANALYSIS + "", sender)) {
if (!Check.isTrue(ConditionUtils.pluginHasViewCapability(), Phrase.ERROR_WEBSERVER_OFF_ANALYSIS.toString(), sender)) {
return true;
}
if (!Check.isTrue(analysisCache.isAnalysisEnabled(), Phrase.ERROR_ANALYSIS_DISABLED_TEMPORARILY + "", sender)) {
if (!analysisCache.isCached()) {
return true;
}
if (!Check.isTrue(analysisCache.isAnalysisEnabled(), Phrase.ERROR_ANALYSIS_DISABLED_TEMPORARILY.toString(), sender)
&& !analysisCache.isCached()) {
return true;
}
updateCache();
runMessageSenderTask(sender);

View File

@ -73,7 +73,7 @@ public class ManageRestoreCommand extends SubCommand {
public void run() {
try {
String backupDBName = args[0];
boolean containsDBFileExtension = backupDBName.contains(".db");
boolean containsDBFileExtension = backupDBName.endsWith(".db");
File backupDBFile = new File(plugin.getDataFolder(), backupDBName + (containsDBFileExtension ? "" : ".db"));
if (!Check.isTrue(Verify.exists(backupDBFile), Phrase.MANAGE_ERROR_BACKUP_FILE_NOT_FOUND + " " + args[0], sender)) {
@ -81,7 +81,7 @@ public class ManageRestoreCommand extends SubCommand {
}
if (containsDBFileExtension) {
backupDBName = backupDBName.replace(".db", "");
backupDBName = backupDBName.substring(0, backupDBName.length() - 3);
}
SQLiteDB backupDB = new SQLiteDB(plugin, backupDBName);

View File

@ -25,7 +25,7 @@ import java.util.Map;
* @author Rsl1122
* @since 3.5.2
*/
public class AnalysisData extends RawData<AnalysisData> {
public class AnalysisData extends RawData {
private final ActivityPart activityPart;
private final CommandUsagePart commandUsagePart;
@ -136,7 +136,7 @@ public class AnalysisData extends RawData<AnalysisData> {
addValue("version", planVersion);
final List<RawData> parts = getAllParts();
parts.forEach((part) -> {
parts.forEach(part -> {
try {
Benchmark.start("Analysis Phase: " + part.getClass().getSimpleName());
part.analyseData();

View File

@ -119,17 +119,20 @@ public class TPS {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TPS other = (TPS) obj;
return this.date == other.date
&& Double.doubleToLongBits(this.tps) == Double.doubleToLongBits(other.tps)
return date == other.date
&& Double.compare(this.tps, other.tps) == 0
&& this.players == other.players
&& this.cpuUsage == other.cpuUsage;
&& Double.compare(cpuUsage, other.cpuUsage) == 0;
}
@Override

View File

@ -180,7 +180,7 @@ public class UserData {
public String toString() {
try {
return "{" + "accessing:" + accessing + "|uuid:" + uuid + "|ips:" + ips + "|nicknames:" + nicknames + "|lastNick:" + lastNick + "|registered:" + registered + "|lastPlayed:" + lastPlayed + "|playTime:" + playTime + "|loginTimes:" + loginTimes + "|timesKicked:" + timesKicked + "|lastGmSwapTime:" + lastGmSwapTime + "|lastGamemode:" + lastGamemode + "|gmTimes:" + gmTimes + "|isOp:" + isOp + "|isBanned:" + isBanned + "|geolocation:" + geolocation + "|mobKills:" + mobKills + "|playerKills:" + playerKills + "|deaths:" + deaths + "|name:" + name + "|isOnline:" + isOnline + "|currentSession:" + currentSession + "|sessions:" + sessions + '}';
} catch (Throwable e) {
} catch (Exception e) {
return "UserData: Error on toString:" + e;
}
}
@ -752,41 +752,6 @@ public class UserData {
this.lastNick = lastNick;
}
@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;
// if (this.lastPlayed != other.lastPlayed) {
// return false;
// }
return this.registered == other.registered
&& this.playTime == other.playTime
&& this.loginTimes == other.loginTimes
&& this.timesKicked == other.timesKicked
&& this.lastGmSwapTime == other.lastGmSwapTime
&& this.mobKills == other.mobKills
&& this.deaths == other.deaths
&& Objects.equals(this.lastNick, other.lastNick)
&& Objects.equals(this.name, other.name)
&& Objects.equals(this.uuid, other.uuid)
&& Objects.equals(this.ips, other.ips)
&& Objects.equals(this.nicknames, other.nicknames)
&& Objects.equals(this.lastGamemode, other.lastGamemode)
&& Objects.equals(this.gmTimes, other.gmTimes)
&& Objects.equals(this.playerKills, other.playerKills)
&& Objects.equals(this.sessions, other.sessions);
}
/**
* Check whether or not the object should be cleared from cache after it has
* been saved.
@ -814,4 +779,65 @@ public class UserData {
public void setGeolocation(String geolocation) {
this.geolocation = geolocation;
}
@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 + ips.hashCode();
result = 31 * result + nicknames.hashCode();
result = 31 * result + lastNick.hashCode();
result = 31 * result + (int) (registered ^ (registered >>> 32));
result = 31 * result + (int) (lastPlayed ^ (lastPlayed >>> 32));
result = 31 * result + (int) (playTime ^ (playTime >>> 32));
result = 31 * result + loginTimes;
result = 31 * result + timesKicked;
result = 31 * result + (int) (lastGmSwapTime ^ (lastGmSwapTime >>> 32));
result = 31 * result + lastGamemode.hashCode();
result = 31 * result + gmTimes.hashCode();
result = 31 * result + (isOp ? 1 : 0);
result = 31 * result + (isBanned ? 1 : 0);
result = 31 * result + geolocation.hashCode();
result = 31 * result + mobKills;
result = 31 * result + playerKills.hashCode();
result = 31 * result + deaths;
result = 31 * result + name.hashCode();
result = 31 * result + (isOnline ? 1 : 0);
result = 31 * result + currentSession.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 this.registered == other.registered
&& this.playTime == other.playTime
&& this.loginTimes == other.loginTimes
&& this.timesKicked == other.timesKicked
&& this.lastGmSwapTime == other.lastGmSwapTime
&& this.mobKills == other.mobKills
&& this.deaths == other.deaths
&& Objects.equals(this.lastNick, other.lastNick)
&& Objects.equals(this.name, other.name)
&& Objects.equals(this.uuid, other.uuid)
&& Objects.equals(this.ips, other.ips)
&& Objects.equals(this.nicknames, other.nicknames)
&& Objects.equals(this.lastGamemode, other.lastGamemode)
&& Objects.equals(this.gmTimes, other.gmTimes)
&& Objects.equals(this.playerKills, other.playerKills)
&& Objects.equals(this.sessions, other.sessions);
}
}

View File

@ -30,7 +30,7 @@ public class HookHandler {
configHandler = new PluginConfigSectionHandler(plugin);
try {
Bridge.hook(this);
} catch (Throwable e) {
} catch (Exception e) {
Log.toLog(this.getClass().getName(), e);
Log.error("Plan Plugin Bridge not included in the plugin jar.");
}

View File

@ -36,7 +36,7 @@ import java.util.stream.Collectors;
* @author Rsl1122
* @since 3.5.2
*/
public class ActivityPart extends RawData<ActivityPart> {
public class ActivityPart extends RawData {
private final JoinInfoPart joins;
private final TPSPart tpsPart;

View File

@ -22,7 +22,7 @@ import java.util.Map;
* @author Rsl1122
* @since 3.5.2
*/
public class CommandUsagePart extends RawData<CommandUsagePart> {
public class CommandUsagePart extends RawData {
private final Map<String, Integer> commandUsage;

View File

@ -20,7 +20,7 @@ import java.util.Arrays;
* @author Rsl1122
* @since 3.5.2
*/
public class GamemodePart extends RawData<GamemodePart> {
public class GamemodePart extends RawData {
private long survivalTime;
private long creativeTime;

View File

@ -15,7 +15,7 @@ import java.util.Map;
* @author Rsl1122
* @since 3.5.2
*/
public class GeolocationPart extends RawData<GeolocationPart> {
public class GeolocationPart extends RawData {
private final Map<String, Integer> geoLocations;
private final Map<String, String> geoCodes;

View File

@ -25,7 +25,7 @@ import java.util.stream.Collectors;
* @author Rsl1122
* @since 3.5.2
*/
public class JoinInfoPart extends RawData<JoinInfoPart> {
public class JoinInfoPart extends RawData {
private final Map<UUID, List<SessionData>> sessions;
private final List<Long> registered;

View File

@ -22,7 +22,7 @@ import java.util.UUID;
* @author Rsl1122
* @since 3.5.2
*/
public class KillPart extends RawData<KillPart> {
public class KillPart extends RawData {
private final PlayerCountPart playerCount;
private final Map<UUID, List<KillData>> playerKills;

View File

@ -19,7 +19,7 @@ import java.util.UUID;
* @author Rsl1122
* @since 3.5.2
*/
public class PlayerCountPart extends RawData<PlayerCountPart> {
public class PlayerCountPart extends RawData {
private final Set<UUID> uuids;
private final Set<UUID> ops;

View File

@ -13,7 +13,7 @@ import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
* @author Rsl1122
* @since 3.5.2
*/
public class PlaytimePart extends RawData<PlaytimePart> {
public class PlaytimePart extends RawData {
private final PlayerCountPart playerCount;
private long totalPlaytime;

View File

@ -9,11 +9,10 @@ import java.util.Map;
/**
* Extending objects should represent, add together and analyse data.
*
* @param <T> The extending class, return value for get method.
* @author Rsl1122
* @since 3.5.2
*/
public abstract class RawData<T extends RawData> {
public abstract class RawData {
private final Map<String, String> replaceMap;
@ -79,10 +78,10 @@ public abstract class RawData<T extends RawData> {
private String addPlaceholderSigns(String placeholder) {
if (placeholder.charAt(0) != '%') {
placeholder = '%' + placeholder;
placeholder = "%" + placeholder;
}
if (placeholder.charAt(placeholder.length() - 1) != '%') {
placeholder += '%';
placeholder += "%";
}
return placeholder;
}

View File

@ -26,7 +26,7 @@ import java.util.List;
* @author Rsl1122
* @since 3.5.2
*/
public class TPSPart extends RawData<TPSPart> {
public class TPSPart extends RawData {
private final List<TPS> tpsData;

View File

@ -3,7 +3,7 @@ package main.java.com.djrapitops.plan.data.cache;
import main.java.com.djrapitops.plan.data.UserData;
/**
* This abstract class can be extended with anything as the process method and
* 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
@ -12,7 +12,7 @@ import main.java.com.djrapitops.plan.data.UserData;
* @author Rsl1122
* @since 2.6.0
*/
public abstract class DBCallableProcessor {
public interface DBCallableProcessor {
/**
* Method used to do multiple things to UserData objects such as Caching,
@ -21,5 +21,5 @@ public abstract class DBCallableProcessor {
* @param data UserData object given to the DBCallableProcessor by the
* method it was given as parameter to.
*/
public abstract void process(UserData data);
void process(UserData data);
}

View File

@ -384,7 +384,7 @@ public class DataCacheHandler extends SessionCache {
*/
public void saveHandlerDataToCache() {
final List<IPlayer> onlinePlayers = plugin.fetch().getOnlinePlayers();
onlinePlayers.forEach((p) -> saveHandlerDataToCache(p, false));
onlinePlayers.forEach(p -> saveHandlerDataToCache(p, false));
}
private void saveHandlerDataToCache(IPlayer player, boolean pool) {
@ -477,9 +477,9 @@ public class DataCacheHandler extends SessionCache {
/**
* Used to get the contents of the cache.
*
* @return The HashMap containing all Cached UserData
* @return The Map containing all Cached UserData
*/
public HashMap<UUID, UserData> getDataCache() {
public Map<UUID, UserData> getDataCache() {
return dataCache;
}

View File

@ -7,6 +7,7 @@ import main.java.com.djrapitops.plan.utilities.Benchmark;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
@ -21,6 +22,14 @@ import java.util.Map;
* @since 3.5.5
*/
public class GeolocationCacheHandler {
/**
* Constructor used to hide the public constructor
*/
private GeolocationCacheHandler() {
throw new IllegalStateException("Utility class");
}
private static final Cache<String, String> geolocationCache = CacheBuilder.newBuilder()
.maximumSize(10000)
.build();
@ -71,12 +80,20 @@ public class GeolocationCacheHandler {
*/
private static String getUncachedCountry(String ipAddress) {
Benchmark.start("getUncachedCountry");
URL url;
String urlString = "http://freegeoip.net/csv/" + ipAddress;
try {
URL url = new URL("http://freegeoip.net/csv/" + ipAddress);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
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";
}
try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
String resultLine = in.readLine();
Log.debug(resultLine);
in.close();
Log.debug("Result for country request for " + ipAddress + ": " + resultLine);
String[] results = resultLine.split(",");
String result = results[2];

View File

@ -1,6 +1,7 @@
package main.java.com.djrapitops.plan.data.cache.queue;
import com.djrapitops.plugin.task.AbsRunnable;
import main.java.com.djrapitops.plan.Log;
import java.util.concurrent.BlockingQueue;
@ -34,6 +35,8 @@ public abstract class Consumer<T> extends AbsRunnable {
consume(queue.take());
}
} catch (InterruptedException ex) {
Log.error("Consumer interrupted: " + ex.getCause());
Thread.currentThread().interrupt();
}
}

View File

@ -50,7 +50,7 @@ public class DataCacheGetQueue extends Queue<Map<UUID, List<DBCallableProcessor>
}
public boolean containsUUIDtoBeCached(UUID uuid) {
return uuid != null && new ArrayList<>(queue).stream().anyMatch((map) -> (map.get(uuid) != null && map.get(uuid).size() >= 2));
return uuid != null && new ArrayList<>(queue).stream().anyMatch(map -> (map.get(uuid) != null && map.get(uuid).size() >= 2));
}
}
@ -70,11 +70,15 @@ class GetConsumer extends Consumer<Map<UUID, List<DBCallableProcessor>>> {
}
try {
for (UUID uuid : processors.keySet()) {
for (Map.Entry<UUID, List<DBCallableProcessor>> entrySet : processors.entrySet()) {
UUID uuid = entrySet.getKey();
if (uuid == null) {
continue;
}
List<DBCallableProcessor> processorsList = processors.get(uuid);
List<DBCallableProcessor> processorsList = entrySet.getValue();
if (processorsList != null) {
Log.debug(uuid + ": Get, For:" + processorsList.size());
try {

View File

@ -116,13 +116,11 @@ class SaveConsumer extends Consumer<UserData> {
db.saveUserData(data);
data.stopAccessing();
Log.debug(uuid + ": Saved!");
if (data.shouldClearAfterSave()) {
if (handler != null) {
handler.getClearTask().scheduleForClear(uuid);
}
if (data.shouldClearAfterSave()
&& handler != null) {
handler.getClearTask().scheduleForClear(uuid);
}
} catch (SQLException ex) {
// queue.add(data);
Log.toLog(this.getClass().getName(), ex);
}
}
@ -132,6 +130,7 @@ class SaveConsumer extends Consumer<UserData> {
if (db != null) {
db = null;
}
if (handler != null) {
handler = null;
}

View File

@ -11,15 +11,21 @@ import main.java.com.djrapitops.plan.data.UserData;
*/
public class ChatHandling {
/**
* Constructor used to hide the public constructor
*/
private ChatHandling() {
throw new IllegalStateException("Utility class");
}
/**
* Processes the information of the Event and changes UserData object
* accordingly.
*
* @param data UserData of the player.
* @param nickname Nickname of the player during the event.
* @param msg Message sent by the player.
*/
public static void processChatInfo(UserData data, String nickname, String msg) {
public static void processChatInfo(UserData data, String nickname) {
data.addNickname(nickname);
}
}

View File

@ -36,7 +36,7 @@ public class ImportUtils {
try {
importers.put("ontime", new OnTimeImporter());
importers.put("offline", new OfflinePlayerImporter());
} catch (Throwable e) {
} catch (Exception e) {
Log.toLog("ImportUtils.getImporters", e);
Log.error("Plan Plugin Bridge not included in the plugin jar.");
}

View File

@ -34,7 +34,7 @@ public class ChatInfo extends HandlingInfo {
if (!uData.getUuid().equals(uuid)) {
return false;
}
ChatHandling.processChatInfo(uData, nickname, message);
ChatHandling.processChatInfo(uData, nickname);
return true;
}
}

View File

@ -60,10 +60,10 @@ public class PlanDeathEventListener implements Listener {
Material itemInHand;
try {
itemInHand = killer.getInventory().getItemInMainHand().getType();
} catch (Throwable e) {
} catch (Exception e) {
try {
itemInHand = killer.getInventory().getItemInHand().getType(); // Support for non dual wielding versions.
} catch (Throwable e2) {
} catch (Exception e2) {
itemInHand = Material.AIR;
}
}

View File

@ -19,6 +19,13 @@ import java.util.Map.Entry;
*/
public class DBUtils {
/**
* Constructor used to hide the public constructor
*/
private DBUtils() {
throw new IllegalStateException("Utility class");
}
private static final int BATCH_SIZE = 2048;
/**

View File

@ -15,6 +15,7 @@ import main.java.com.djrapitops.plan.utilities.FormatUtils;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
@ -63,12 +64,22 @@ public abstract class SQLDB extends Database {
plugin.getRunnableFactory().createNew(new AbsRunnable("DBConnectionPingTask " + getName()) {
@Override
public void run() {
Statement statement = null;
try {
if (connection != null && !connection.isClosed()) {
connection.createStatement().execute("/* ping */ SELECT 1");
statement = connection.createStatement();
statement.execute("/* ping */ SELECT 1");
}
} catch (SQLException e) {
connection = getNewConnection();
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
Log.error("Error at closing statement");
}
}
}
}
}).runTaskTimerAsynchronously(60 * 20, 60 * 20);
@ -113,27 +124,34 @@ public abstract class SQLDB extends Database {
getVersion();
newDatabase = false;
} catch (Exception e) {
}
if (!versionTable.createTable()) {
Log.error("Failed to create table: " + versionTable.getTableName());
return false;
}
if (newDatabase) {
Log.info("New Database created.");
setVersion(7);
}
Benchmark.start("Database: Create tables");
for (Table table : getAllTables()) {
if (!table.createTable()) {
Log.error("Failed to create table: " + table.getTableName());
return false;
}
}
if (!securityTable.createTable()) {
Log.error("Failed to create table: " + securityTable.getTableName());
return false;
}
Benchmark.stop("Database: Create tables");
if (!newDatabase && getVersion() < 7) {
setVersion(7);
}
@ -304,7 +322,7 @@ public abstract class SQLDB extends Database {
List<String> nicknames = nicknamesTable.getNicknames(userId);
data.addNicknames(nicknames);
if (nicknames.size() > 0) {
if (!nicknames.isEmpty()) {
data.setLastNick(nicknames.get(nicknames.size() - 1));
}
@ -397,13 +415,16 @@ public abstract class SQLDB extends Database {
Map<Integer, List<SessionData>> sessions = new HashMap<>();
Map<Integer, Map<String, Long>> gmTimes = new HashMap<>();
// Put to dataset
for (UUID uuid : userDatas.keySet()) {
for (Map.Entry<UUID, UserData> entrySet : userDatas.entrySet()) {
UUID uuid = entrySet.getKey();
UserData uData = entrySet.getValue();
Integer id = userIds.get(uuid);
UserData uData = userDatas.get(uuid);
if (id == -1) {
Log.debug("User not seen before, saving last: " + uuid);
continue;
}
uData.access();
nicknames.put(id, new HashSet<>(uData.getNicknames()));
lastNicks.put(id, uData.getLastNick());
@ -464,7 +485,6 @@ public abstract class SQLDB extends Database {
checkConnection();
tpsTable.clean();
locationsTable.removeAllData();
// sessionsTable.clean();
Log.info("Clean complete.");
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);

View File

@ -90,14 +90,17 @@ public class CommandUseTable extends Table {
insertCommands(newData);
Map<String, Integer> updateData = new HashMap<>(data);
updateData.keySet().removeAll(newData.keySet());
for (String cmd : saved.keySet()) {
Integer toSave = updateData.get(cmd);
if (toSave != null) {
if (toSave <= saved.get(cmd)) {
updateData.remove(cmd);
}
for (Map.Entry<String, Integer> entrySet : saved.entrySet()) {
String cmd = entrySet.getKey();
Integer toSave = entrySet.getValue();
if (toSave == null || toSave > saved.get(cmd)) {
continue;
}
updateData.remove(cmd);
}
updateCommands(updateData);
Benchmark.stop("Database: Save Commanduse");
}
@ -108,16 +111,20 @@ public class CommandUseTable extends Table {
String updateStatement = "UPDATE " + tableName + " SET " + columnTimesUsed + "=? WHERE (" + columnCommand + "=?)";
statement = prepareStatement(updateStatement);
boolean commitRequired = false;
for (String key : data.keySet()) {
Integer amount = data.get(key);
for (Map.Entry<String, Integer> entrySet : data.entrySet()) {
String key = entrySet.getKey();
Integer amount = entrySet.getValue();
if (key.length() > 20) {
continue;
}
statement.setInt(1, amount);
statement.setString(2, key);
statement.addBatch();
commitRequired = true;
}
if (commitRequired) {
statement.executeBatch();
}
@ -135,16 +142,20 @@ public class CommandUseTable extends Table {
+ ") VALUES (?, ?)";
statement = prepareStatement(insertStatement);
boolean commitRequired = false;
for (String key : data.keySet()) {
Integer amount = data.get(key);
for (Map.Entry<String, Integer> entrySet : data.entrySet()) {
String key = entrySet.getKey();
Integer amount = entrySet.getValue();
if (key.length() > 20) {
continue;
}
statement.setString(1, key);
statement.setInt(2, amount);
statement.addBatch();
commitRequired = true;
}
if (commitRequired) {
statement.executeBatch();
}

View File

@ -208,20 +208,20 @@ public class GMTimesTable extends Table {
+ columnSpectatorTime + "=? "
+ " WHERE (" + columnUserID + "=?)");
boolean commitRequired = false;
for (Integer id : gamemodeTimes.keySet()) {
for (Map.Entry<Integer, Map<String, Long>> entrySet : gamemodeTimes.entrySet()) {
Integer id = entrySet.getKey();
if (!savedIDs.contains(id)) {
continue;
}
statement.setInt(5, id);
for (int i = 0; i < gms.length; i++) {
try {
Map<String, Long> times = gamemodeTimes.get(id);
Map<String, Long> times = entrySet.getValue();
Long time = times.get(gms[i]);
if (time != null) {
statement.setLong(i + 1, time);
} else {
statement.setLong(i + 1, 0);
}
statement.setLong(i + 1, time != null ? time : 0);
} catch (NoSuchFieldError e) {
statement.setLong(i + 1, 0);
}
@ -229,13 +229,16 @@ public class GMTimesTable extends Table {
statement.addBatch();
commitRequired = true;
}
if (commitRequired) {
statement.executeBatch();
}
gamemodeTimes.keySet().removeAll(savedIDs);
} finally {
close(statement);
}
addNewGMTimesRows(gamemodeTimes);
Benchmark.stop("Database: Save GMTimes");
}
@ -257,17 +260,16 @@ public class GMTimesTable extends Table {
+ columnSpectatorTime
+ ") VALUES (?, ?, ?, ?, ?)");
boolean commitRequired = false;
for (Integer id : gamemodeTimes.keySet()) {
for (Map.Entry<Integer, Map<String, Long>> entrySet : gamemodeTimes.entrySet()) {
Integer id = entrySet.getKey();
statement.setInt(1, id);
for (int i = 0; i < gms.length; i++) {
try {
Map<String, Long> times = gamemodeTimes.get(id);
Map<String, Long> times = entrySet.getValue();
Long time = times.get(gms[i]);
if (time != null) {
statement.setLong(i + 2, time);
} else {
statement.setLong(i + 2, 0);
}
statement.setLong(i + 1, time != null ? time : 0);
} catch (NoSuchFieldError e) {
statement.setLong(i + 2, 0);
}
@ -275,6 +277,7 @@ public class GMTimesTable extends Table {
statement.addBatch();
commitRequired = true;
}
if (commitRequired) {
statement.executeBatch();
}
@ -300,15 +303,13 @@ public class GMTimesTable extends Table {
for (int i = 0; i < gms.length; i++) {
try {
Long time = gamemodeTimes.get(gms[i]);
if (time != null) {
statement.setLong(i + 2, time);
} else {
statement.setLong(i + 2, 0);
}
statement.setLong(i + 2, time != null ? time : 0);
} catch (NoSuchFieldError e) {
statement.setLong(i + 2, 0);
}
}
statement.execute();
} finally {
close(statement);

View File

@ -83,9 +83,11 @@ public class IPsTable extends Table {
set = statement.executeQuery();
List<InetAddress> ips = new ArrayList<>();
while (set.next()) {
String ipAddressName = set.getString(columnIP);
try {
ips.add(InetAddress.getByName(set.getString(columnIP)));
ips.add(InetAddress.getByName(ipAddressName));
} catch (UnknownHostException e) {
Log.error("Host not found at getIPAddresses: " + ipAddressName); //Shouldn't ever happen
}
}
return ips;
@ -105,11 +107,14 @@ public class IPsTable extends Table {
if (ips == null) {
return;
}
Benchmark.start("Database: Save Ips");
ips.removeAll(getIPAddresses(userId));
if (ips.isEmpty()) {
return;
}
PreparedStatement statement = null;
try {
statement = prepareStatement("INSERT INTO " + tableName + " ("
@ -118,14 +123,18 @@ public class IPsTable extends Table {
+ ") VALUES (?, ?)");
boolean commitRequired = false;
for (InetAddress ip : ips) {
if (ip == null) {
continue;
}
statement.setInt(1, userId);
statement.setString(2, ip.getHostAddress());
statement.addBatch();
commitRequired = true;
}
if (commitRequired) {
statement.executeBatch();
}
@ -144,26 +153,36 @@ public class IPsTable extends Table {
if (ids == null || ids.isEmpty()) {
return new HashMap<>();
}
Benchmark.start("Database: Get Ips Multiple");
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement("SELECT * FROM " + tableName);
set = statement.executeQuery();
Map<Integer, Set<InetAddress>> ips = new HashMap<>();
for (Integer id : ids) {
ips.put(id, new HashSet<>());
}
while (set.next()) {
Integer id = set.getInt(columnUserID);
if (!ids.contains(id)) {
continue;
}
String ipAddressName = set.getString(columnIP);
try {
ips.get(id).add(InetAddress.getByName(set.getString(columnIP)));
ips.get(id).add(InetAddress.getByName(ipAddressName));
} catch (UnknownHostException e) {
Log.error("Host not found at getIPAddresses: " + ipAddressName); //Shouldn't ever happen
}
}
return ips;
} finally {
close(set);
@ -190,19 +209,25 @@ public class IPsTable extends Table {
+ ") VALUES (?, ?)");
boolean commitRequired = false;
int i = 0;
for (Integer id : ips.keySet()) {
Set<InetAddress> ipAddresses = ips.get(id);
for (Map.Entry<Integer, Set<InetAddress>> entrySet : ips.entrySet()) {
Integer id = entrySet.getKey();
Set<InetAddress> ipAddresses = entrySet.getValue();
Set<InetAddress> s = saved.get(id);
if (s != null) {
ipAddresses.removeAll(s);
}
if (ipAddresses.isEmpty()) {
continue;
}
for (InetAddress ip : ipAddresses) {
if (ip == null) {
continue;
}
statement.setInt(1, id);
statement.setString(2, ip.getHostAddress());
statement.addBatch();
@ -210,13 +235,14 @@ public class IPsTable extends Table {
i++;
}
}
if (commitRequired) {
Log.debug("Executing ips batch: " + i);
statement.executeBatch();
}
Benchmark.stop("Database: Save Ips Multiple");
} finally {
close(statement);
Benchmark.stop("Database: Save Ips Multiple");
}
}
}

View File

@ -93,7 +93,7 @@ public class KillsTable extends Table {
List<KillData> killData = new ArrayList<>();
while (set.next()) {
int victimID = set.getInt(columnVictimUserID);
UUID victimUUID = usersTable.getUserUUID(victimID + "");
UUID victimUUID = usersTable.getUserUUID(String.valueOf(victimID));
killData.add(new KillData(victimUUID, victimID, set.getString(columnWeapon), set.getLong(columnDate)));
}
return killData;
@ -131,20 +131,24 @@ public class KillsTable extends Table {
if (kill == null) {
continue;
}
statement.setInt(1, userId);
int victimUserID = kill.getVictimUserID();
if (victimUserID == -1) {
victimUserID = db.getUsersTable().getUserId(kill.getVictim());
if (victimUserID == -1) {
continue;
}
}
statement.setInt(2, victimUserID);
statement.setString(3, kill.getWeapon());
statement.setLong(4, kill.getDate());
statement.addBatch();
commitRequired = true;
}
if (commitRequired) {
statement.executeBatch();
}
@ -200,6 +204,7 @@ public class KillsTable extends Table {
if (kills == null || kills.isEmpty()) {
return;
}
Benchmark.start("Database: Save Kills multiple");
Map<Integer, List<KillData>> saved = getPlayerKills(kills.keySet(), uuids);
@ -213,16 +218,22 @@ public class KillsTable extends Table {
+ ") VALUES (?, ?, ?, ?)");
boolean commitRequired = false;
int i = 0;
for (Integer id : kills.keySet()) {
List<KillData> playerKills = kills.get(id);
for (Map.Entry<Integer, List<KillData>> entrySet : kills.entrySet()) {
Integer id = entrySet.getKey();
List<KillData> playerKills = entrySet.getValue();
List<KillData> s = saved.get(id);
if (s != null) {
playerKills.removeAll(s);
}
for (KillData kill : playerKills) {
if (kill == null) {
continue;
}
statement.setInt(1, id);
int victimUserID = kill.getVictimUserID();
if (victimUserID == -1) {
@ -230,11 +241,14 @@ public class KillsTable extends Table {
.stream().filter(e -> e.getValue().equals(kill.getVictim()))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
if (matchingIds.isEmpty()) {
continue;
}
victimUserID = matchingIds.get(0);
}
statement.setInt(2, victimUserID);
statement.setString(3, kill.getWeapon());
statement.setLong(4, kill.getDate());
@ -242,14 +256,15 @@ public class KillsTable extends Table {
commitRequired = true;
i++;
}
if (commitRequired) {
Log.debug("Executing kills batch: " + i);
statement.executeBatch();
}
}
Benchmark.stop("Database: Save Kills multiple");
} finally {
close(statement);
Benchmark.stop("Database: Save Kills multiple");
}
}
}

View File

@ -21,6 +21,7 @@ public class LocationsTable extends Table {
/**
* @param db
* @param usingMySQL
* @deprecated Deprecated because it isn't used anymore
*/
@Deprecated
public LocationsTable(SQLDB db, boolean usingMySQL) {

View File

@ -61,10 +61,8 @@ public class NicknamesTable extends Table {
} else {
query = "ALTER TABLE " + tableName + " ADD COLUMN " + columnCurrent + " boolean NOT NULL DEFAULT 0";
}
try {
execute(query);
} catch (Exception e) {
}
executeUnsafe(query);
}
/**
@ -201,11 +199,15 @@ public class NicknamesTable extends Table {
lastNicks.put(id, nickname);
}
}
for (Integer id : lastNicks.keySet()) {
String lastNick = lastNicks.get(id);
//TODO figure out what the heck that method does @Rsl1122
for (Map.Entry<Integer, String> entrySet : lastNicks.entrySet()) {
Integer id = entrySet.getKey();
String lastNick = entrySet.getValue();
List<String> list = nicks.get(id);
list.remove(lastNick);
list.add(lastNick);
list.remove(lastNick); //NOTE: Remove here?
list.add(lastNick); //NOTE: And add here again?
}
return nicks;
@ -225,7 +227,9 @@ public class NicknamesTable extends Table {
if (nicknames == null || nicknames.isEmpty()) {
return;
}
Benchmark.start("Database: Save Nicknames Multiple");
Map<Integer, List<String>> saved = getNicknames(nicknames.keySet());
PreparedStatement statement = null;
try {
@ -235,16 +239,22 @@ public class NicknamesTable extends Table {
+ columnCurrent + ", "
+ columnNick
+ ") VALUES (?, ?, ?)");
for (Integer id : nicknames.keySet()) {
Set<String> newNicks = nicknames.get(id);
for (Map.Entry<Integer, Set<String>> entrySet : nicknames.entrySet()) {
Integer id = entrySet.getKey();
Set<String> newNicks = entrySet.getValue();
String lastNick = lastNicks.get(id);
List<String> s = saved.get(id);
if (s != null) {
newNicks.removeAll(s);
}
if (newNicks.isEmpty()) {
continue;
}
for (String name : newNicks) {
statement.setInt(1, id);
statement.setInt(2, (name.equals(lastNick)) ? 1 : 0);
@ -253,6 +263,7 @@ public class NicknamesTable extends Table {
commitRequired = true;
}
}
if (commitRequired) {
statement.executeBatch();
}

View File

@ -190,20 +190,27 @@ public class SessionsTable extends Table {
if (sessions == null || sessions.isEmpty()) {
return;
}
Benchmark.start("Database: Save Sessions multiple");
Map<Integer, List<SessionData>> saved = getSessionData(sessions.keySet());
for (Integer id : sessions.keySet()) {
List<SessionData> sessionList = sessions.get(id);
for (Map.Entry<Integer, List<SessionData>> entrySet : sessions.entrySet()) {
Integer id = entrySet.getKey();
List<SessionData> sessionList = entrySet.getValue();
List<SessionData> s = saved.get(id);
if (s != null) {
sessionList.removeAll(s);
}
if (sessionList.isEmpty()) {
continue;
}
saved.put(id, sessionList);
}
List<List<Container<SessionData>>> batches = splitIntoBatches(sessions);
for (List<Container<SessionData>> batch : batches) {
saveSessionBatch(batch);
}
@ -252,29 +259,40 @@ public class SessionsTable extends Table {
public void clean() throws SQLException {
Map<Integer, Integer> loginTimes = db.getUsersTable().getLoginTimes();
Map<Integer, List<SessionData>> allSessions = getSessionData(loginTimes.keySet());
Benchmark.start("Database: Combine Sessions");
int before = MathUtils.sumInt(allSessions.values().stream().map(List::size));
Log.debug("Sessions before: " + before);
Map<Integer, Integer> beforeM = new HashMap<>();
Map<Integer, Integer> afterM = new HashMap<>();
for (Integer id : allSessions.keySet()) {
List<SessionData> sessions = allSessions.get(id);
for (Map.Entry<Integer, List<SessionData>> entrySet : allSessions.entrySet()) {
Integer id = entrySet.getKey();
List<SessionData> sessions = entrySet.getValue();
beforeM.put(id, sessions.size());
if (sessions.isEmpty()) {
afterM.put(id, 0);
continue;
}
Integer times = loginTimes.get(id);
if (sessions.size() == times) {
afterM.put(id, times);
continue;
}
List<SessionData> combined = ManageUtils.combineSessions(sessions, times);
afterM.put(id, combined.size());
allSessions.put(id, combined);
}
int after = MathUtils.sumInt(allSessions.values().stream().map(List::size));
Log.debug("Sessions after: " + after);
if (before - after > 50) {
Benchmark.start("Database: Save combined sessions");
for (Integer id : new HashSet<>(allSessions.keySet())) {
@ -287,6 +305,7 @@ public class SessionsTable extends Table {
saveSessionData(allSessions);
Benchmark.stop("Database: Save combined sessions");
}
Benchmark.stop("Database: Combine Sessions");
Log.info("Combined " + (before - after) + " sessions.");
}

View File

@ -10,6 +10,7 @@ import main.java.com.djrapitops.plan.utilities.MiscUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
@ -68,13 +69,21 @@ public abstract class Table {
}
/**
* @param statement
* @param statementString
* @return
* @throws SQLException
*/
protected boolean execute(String statement) throws SQLException {
protected boolean execute(String statementString) throws SQLException {
Connection connection = getConnection();
return connection.createStatement().execute(statement);
Statement statement = null;
try {
statement = connection.createStatement();
return statement.execute(statementString);
} finally {
if (statement != null) {
statement.close();
}
}
}
/**

View File

@ -23,9 +23,15 @@ public class UsersTable extends Table {
private final String columnID;
private final String columnUUID;
@Deprecated // Removed in 3.5.2
/**
* @deprecated removed in 3.5.2
*/
@Deprecated
private final String columnDemAge;
@Deprecated // Removed in 3.5.2
/**
* @deprecated removed in 3.5.2
*/
@Deprecated
private final String columnDemGender;
private final String columnGeolocation;
private final String columnLastGM;

View File

@ -27,12 +27,12 @@ public enum Html {
COLOR_7("<span class=\"gray\">"),
COLOR_8("<span class=\"darkgray\">"),
COLOR_9("<span class=\"blue\">"),
COLOR_a("<span class=\"green\">"),
COLOR_b("<span class=\"aqua\">"),
COLOR_c("<span class=\"red\">"),
COLOR_d("<span class=\"pink\">"),
COLOR_e("<span class=\"yellow\">"),
COLOR_f("<span class=\"white\">"),
COLOR_A("<span class=\"green\">"),
COLOR_B("<span class=\"aqua\">"),
COLOR_C("<span class=\"red\">"),
COLOR_D("<span class=\"pink\">"),
COLOR_E("<span class=\"yellow\">"),
COLOR_F("<span class=\"white\">"),
//
FONT_AWESOME_ICON("<i class=\"fa fa-REPLACE0\" aria-hidden=\"true\"></i>"),
MINOTAR_SMALL_IMG("<img style=\"float: left; padding: 2px 2px 0px 2px\" alt=\"" + REPLACE0 + "\" src=\"https://minotar.net/avatar/" + REPLACE0 + "/19\">"),
@ -115,19 +115,21 @@ public enum Html {
* @param localeFile
*/
public static void loadLocale(File localeFile) {
try {
Scanner localeScanner = new Scanner(localeFile, "UTF-8");
try (Scanner localeScanner = new Scanner(localeFile, "UTF-8")){
List<String> localeRows = new ArrayList<>();
boolean html = false;
while (localeScanner.hasNextLine()) {
String line = localeScanner.nextLine();
if (line.equals("<<<<<<HTML>>>>>>")) {
html = true;
continue;
}
if (!html) {
continue;
}
localeRows.add(line);
}
for (String localeRow : localeRows) {
@ -139,7 +141,7 @@ public enum Html {
}
}
} catch (IOException e) {
Log.error("Something went wrong at loading locale " + localeFile.getAbsoluteFile() + ": " + e.getCause());
}
}

View File

@ -9,6 +9,13 @@ import java.util.List;
*/
public class RecentPlayersButtonsCreator {
/**
* Constructor used to hide the public constructor
*/
private RecentPlayersButtonsCreator() {
throw new IllegalStateException("Utility class");
}
/**
* Creates recent players buttons inside a p-tag.
*

View File

@ -8,6 +8,14 @@ import java.util.List;
import java.util.stream.Collectors;
public class CPUGraphCreator {
/**
* Constructor used to hide the public constructor
*/
private CPUGraphCreator() {
throw new IllegalStateException("Utility class");
}
public static String buildScatterDataString(List<TPS> tpsData, long scale) {
long now = MiscUtils.getTime();
List<Point> points = tpsData.stream()

View File

@ -13,6 +13,13 @@ import java.util.stream.Collectors;
*/
public class NewPlayersGraphCreator {
/**
* Constructor used to hide the public constructor
*/
private NewPlayersGraphCreator() {
throw new IllegalStateException("Utility class");
}
/**
* Creates a scatter data string from given data.
*

View File

@ -8,6 +8,7 @@ import main.java.com.djrapitops.plan.utilities.analysis.Point;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
@ -15,6 +16,13 @@ import java.util.stream.Collectors;
*/
public class PlayerActivityGraphCreator {
/**
* Constructor used to hide the public constructor
*/
private PlayerActivityGraphCreator() {
throw new IllegalStateException("Utility class");
}
public static String buildScatterDataString(List<TPS> tpsData, long scale) {
long now = MiscUtils.getTime();
List<Point> points = tpsData.stream()
@ -40,9 +48,9 @@ public class PlayerActivityGraphCreator {
private static List<SessionData> filterSessions(List<SessionData> sessions, long nowMinusScale) {
return sessions.parallelStream()
.filter(session -> (session != null))
.filter(Objects::nonNull)
.filter(session -> session.isValid() || session.getSessionEnd() == -1)
.filter((session) -> (session.getSessionStart() >= nowMinusScale || session.getSessionEnd() >= nowMinusScale))
.filter(session -> session.getSessionStart() >= nowMinusScale || session.getSessionEnd() >= nowMinusScale)
.distinct()
.collect(Collectors.toList());
}

View File

@ -21,6 +21,13 @@ import java.util.stream.Collectors;
*/
public class PunchCardGraphCreator {
/**
* Constructor used to hide the public constructor
*/
private PunchCardGraphCreator() {
throw new IllegalStateException("Utility class");
}
/**
* @param data
* @return
@ -85,6 +92,7 @@ public class PunchCardGraphCreator {
valueMinusAvg[i][j] = (int) Math.pow(Math.abs(array[i][j] - avg), 2);
}
}
int size = array.length * array[0].length;
int sum = sum(valueMinusAvg);
return Math.sqrt(sum / size);

View File

@ -16,6 +16,13 @@ import java.util.stream.Collectors;
*/
public class RamGraphCreator {
/**
* Constructor used to hide the public constructor
*/
private RamGraphCreator() {
throw new IllegalStateException("Utility class");
}
/**
* Creates a scatter data string from given data.
*

View File

@ -23,13 +23,19 @@ import java.util.Set;
*/
public class ScatterGraphCreator {
/**
* Constructor used to hide the public constructor
*/
private ScatterGraphCreator() {
throw new IllegalStateException("Utility class");
}
public static String scatterGraph(List<Point> points, boolean reduceGapTriangles) {
return scatterGraph(points, reduceGapTriangles, true);
}
public static String scatterGraph(List<Point> points, boolean reduceGapTriangles, boolean reducePoints) {
StringBuilder arrayBuilder = new StringBuilder();
arrayBuilder.append("[");
StringBuilder arrayBuilder = new StringBuilder("[");
if (reducePoints) {
points = DouglasPeuckerAlgorithm.reducePoints(points, 0);
@ -45,7 +51,7 @@ public class ScatterGraphCreator {
long lastDate = (long) lastPoint.getX();
double y = point.getY();
double lastY = lastPoint.getY();
if (y != lastY && Math.abs(lastY - y) > 0.5) {
if (Double.compare(y, lastY) != 0 && Math.abs(lastY - y) > 0.5) {
if (lastDate < date - TimeAmount.MINUTE.ms() * 10L) {
toAdd.add(new Point(lastDate + 1, lastY));
toAdd.add(new Point(date - 1, lastY));

View File

@ -9,7 +9,6 @@ import main.java.com.djrapitops.plan.data.SessionData;
import main.java.com.djrapitops.plan.utilities.analysis.AnalysisUtils;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
@ -18,6 +17,13 @@ import java.util.stream.Collectors;
*/
public class SessionLengthDistributionGraphCreator {
/**
* Constructor used to hide the public constructor
*/
private SessionLengthDistributionGraphCreator() {
throw new IllegalStateException("Utility class");
}
/**
* @param data
* @return
@ -33,15 +39,14 @@ public class SessionLengthDistributionGraphCreator {
*/
public static String[] generateDataArray(Collection<Long> lengths) {
Map<Long, Integer> values = getValues(lengths);
// Map<Long, Integer> scaled = scale(values);
StringBuilder arrayBuilder = buildString(values);
StringBuilder labelBuilder = buildLabels(values);
return new String[]{arrayBuilder.toString(), labelBuilder.toString()};
}
private static StringBuilder buildString(Map<Long, Integer> scaled) {
StringBuilder arrayBuilder = new StringBuilder();
arrayBuilder.append("[");
StringBuilder arrayBuilder = new StringBuilder("[");
long big = MathUtils.getBiggestLong(scaled.keySet());
for (long key = 0; key <= big; key++) {
@ -59,8 +64,7 @@ public class SessionLengthDistributionGraphCreator {
}
private static StringBuilder buildLabels(Map<Long, Integer> scaled) {
StringBuilder arrayBuilder = new StringBuilder();
arrayBuilder.append("[");
StringBuilder arrayBuilder = new StringBuilder("[");
long big = MathUtils.getBiggestLong(scaled.keySet());
for (long key = 0; key <= big; key++) {
@ -81,6 +85,7 @@ public class SessionLengthDistributionGraphCreator {
List<Long> unused = new ArrayList<>(lengths);
Map<Long, Integer> values = new HashMap<>();
long lengthInMinutes = 5;
while (!unused.isEmpty() && lengthInMinutes < 120) {
long length = lengthInMinutes * 60 * 1000;
List<Long> lessThan = unused.stream().filter(l -> l < length).collect(Collectors.toList());
@ -90,13 +95,4 @@ public class SessionLengthDistributionGraphCreator {
}
return values;
}
private static Map<Long, Integer> scale(Map<Long, Integer> values) {
Map<Long, Integer> scaled = new HashMap<>();
int total = MathUtils.sumInt(values.values().stream().map(i -> (Serializable) i));
for (long key : values.keySet()) {
scaled.put(key, (int) ((1.0 * values.get(key) / total) * 100));
}
return scaled;
}
}

View File

@ -14,6 +14,13 @@ import java.util.stream.Collectors;
*/
public class TPSGraphCreator {
/**
* Constructor used to hide the public constructor
*/
private TPSGraphCreator() {
throw new IllegalStateException("Utility class");
}
public static String buildScatterDataStringTPS(List<TPS> tpsData, long scale) {
long now = MiscUtils.getTime();
List<Point> points = tpsData.stream()

View File

@ -16,6 +16,13 @@ import java.util.stream.Collectors;
*/
public class WorldLoadGraphCreator {
/**
* Constructor used to hide the public constructor
*/
private WorldLoadGraphCreator() {
throw new IllegalStateException("Utility class");
}
/**
* Creates scatter graph data of entity load.
*

View File

@ -14,6 +14,13 @@ import java.util.Map;
*/
public class CommandUseTableCreator {
/**
* Constructor used to hide the public constructor
*/
private CommandUseTableCreator() {
throw new IllegalStateException("Utility class");
}
/**
* @param commandUse
* @return

View File

@ -14,6 +14,13 @@ import java.util.List;
*/
public class KillsTableCreator {
/**
* Constructor used to hide the public constructor
*/
private KillsTableCreator() {
throw new IllegalStateException("Utility class");
}
/**
* @param killData
* @return

View File

@ -16,6 +16,13 @@ import java.util.List;
*/
public class PlayersTableCreator {
/**
* Constructor used to hide the public constructor
*/
private PlayersTableCreator() {
throw new IllegalStateException("Utility class");
}
/**
* @param data
* @return

View File

@ -20,6 +20,13 @@ import java.util.UUID;
*/
public class TextUI {
/**
* Constructor used to hide the public constructor
*/
private TextUI() {
throw new IllegalStateException("Utility class");
}
/**
* @param uuid
* @return

View File

@ -28,8 +28,7 @@ public class Authenticator extends BasicAuthenticator {
}
}
private boolean isAuthorized(String user, String passwordRaw, String target) throws IllegalArgumentException, PassEncryptUtil.CannotPerformOperationException, PassEncryptUtil.InvalidHashException, SQLException {
private boolean isAuthorized(String user, String passwordRaw, String target) throws PassEncryptUtil.CannotPerformOperationException, PassEncryptUtil.InvalidHashException, SQLException {
SecurityTable securityTable = plugin.getDB().getSecurityTable();
if (!securityTable.userExists(user)) {
throw new IllegalArgumentException("User Doesn't exist");

View File

@ -19,9 +19,7 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
@ -35,18 +33,13 @@ import java.util.concurrent.Executors;
*/
public class WebSocketServer {
private final int PORT;
private final Plan plugin;
private final DataRequestHandler dataReqHandler;
private boolean enabled = false;
private Socket sslServer;
private HttpServer server;
private final int port;
private boolean shutdown;
private KeyManagerFactory keyManagerFactory;
private TrustManagerFactory trustManagerFactory;
/**
* Class Constructor.
* <p>
@ -56,7 +49,7 @@ public class WebSocketServer {
*/
public WebSocketServer(Plan plugin) {
this.plugin = plugin;
this.PORT = Settings.WEBSERVER_PORT.getNumber();
this.port = Settings.WEBSERVER_PORT.getNumber();
shutdown = false;
dataReqHandler = new DataRequestHandler(plugin);
}
@ -71,8 +64,6 @@ public class WebSocketServer {
}
Log.info(Phrase.WEBSERVER_INIT.toString());
try {
InetAddress ip = InetAddress.getByName(Settings.WEBSERVER_IP.toString());
String keyStorePath = Settings.WEBSERVER_CERTIFICATE_PATH.toString();
if (!keyStorePath.contains(":")) {
keyStorePath = plugin.getDataFolder() + keyStorePath;
@ -82,8 +73,7 @@ public class WebSocketServer {
String alias = Settings.WEBSERVER_CERTIFICATE_ALIAS.toString();
boolean startSuccessful = false;
try {
FileInputStream fIn = new FileInputStream(keyStorePath);
try (FileInputStream fIn = new FileInputStream(keyStorePath)) {
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(fIn, storepass);
@ -91,39 +81,31 @@ public class WebSocketServer {
Log.info("Found Certificate: " + cert.getType());
keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keystore, keypass);
trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(keystore);
server = HttpsServer.create(new InetSocketAddress(PORT), 10);
server = HttpsServer.create(new InetSocketAddress(port), 10);
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyManagerFactory.getKeyManagers(), null/*trustManagerFactory.getTrustManagers()*/, null);
((HttpsServer) server).setHttpsConfigurator(new HttpsConfigurator(sslContext) {
@Override
public void configure(HttpsParameters params) {
// try {
// SSLContext c = SSLContext.getDefault();
SSLEngine engine = sslContext.createSSLEngine();
SSLEngine engine = sslContext.createSSLEngine();
params.setNeedClientAuth(false);
params.setCipherSuites(engine.getEnabledCipherSuites());
params.setProtocols(engine.getEnabledProtocols());
params.setNeedClientAuth(false);
params.setCipherSuites(engine.getEnabledCipherSuites());
params.setProtocols(engine.getEnabledProtocols());
SSLParameters defaultSSLParameters = sslContext.getDefaultSSLParameters();
params.setSSLParameters(defaultSSLParameters);
// } catch (NoSuchAlgorithmException e) {
// Log.error("WebServer: SSL Engine loading Failed.");
// Log.toLog(this.getClass().getName(), e);
// }
SSLParameters defaultSSLParameters = sslContext.getDefaultSSLParameters();
params.setSSLParameters(defaultSSLParameters);
}
});
startSuccessful = true;
} catch (KeyManagementException e) {
Log.error("WebServer: SSL Context Initialization Failed.");
Log.toLog(this.getClass().getName(), e);
} catch (NoSuchAlgorithmException e) {
} catch (KeyManagementException | NoSuchAlgorithmException e) {
Log.error("WebServer: SSL Context Initialization Failed.");
Log.toLog(this.getClass().getName(), e);
} catch (FileNotFoundException e) {
@ -135,7 +117,7 @@ public class WebSocketServer {
Log.toLog(this.getClass().getName(), e);
}
Log.debug("Start Successful: "+startSuccessful);
Log.debug("Start Successful: " + startSuccessful);
if (!startSuccessful) {
return; // TODO Http Server
@ -156,42 +138,9 @@ public class WebSocketServer {
server.setExecutor(Executors.newSingleThreadExecutor());
server.start();
// server = new ServerSocket(PORT, 1, ip);
//
// plugin.getRunnableFactory().createNew(new AbsRunnable("WebServerTask") {
// @Override
// public void run() {
// while (!shutdown) {
// /*SSL*/
// Socket socket = null;
// InputStream input = null;
// OutputStream output = null;
// Request request = null;
// try {
// socket = /*(SSLSocket)*/ server.accept();
// Log.debug("New Socket Connection: " + socket.getInetAddress());
// input = socket.getInputStream();
// output = socket.getOutputStream();
// request = new Request(input);
// Benchmark.start("Webserver Response");
// request.parse();
// Response response = getResponse(request, output);
// Log.debug("Parsed response: " + response.getClass().getSimpleName());
// response.sendStaticResource();
// } catch (IOException | IllegalArgumentException e) {
// } finally {
// MiscUtils.close(input, request, output, socket);
// Benchmark.stop("Webserver Response");
// }
// }
// this.cancel();
// }
// }).runTaskAsynchronously();
enabled = true;
Log.info(Phrase.WEBSERVER_RUNNING.parse(server.getAddress().getPort() + ""));
Log.info(Phrase.WEBSERVER_RUNNING.parse(String.valueOf(server.getAddress().getPort())));
} catch (IllegalArgumentException | IllegalStateException | IOException e) {
Log.toLog(this.getClass().getName(), e);
enabled = false;
@ -307,7 +256,7 @@ public class WebSocketServer {
return dataReqHandler;
}
private boolean isAuthorized(Request request) throws IllegalArgumentException, PassEncryptUtil.CannotPerformOperationException, PassEncryptUtil.InvalidHashException, SQLException {
private boolean isAuthorized(Request request) throws PassEncryptUtil.CannotPerformOperationException, PassEncryptUtil.InvalidHashException, SQLException {
Base64.Decoder decoder = Base64.getDecoder();
String auth = request.getAuthorization();
byte[] decoded = decoder.decode(auth);
@ -320,7 +269,7 @@ public class WebSocketServer {
return isAuthorized(user, passwordRaw, request.getTarget());
}
private boolean isAuthorized(String user, String passwordRaw, String target) throws IllegalArgumentException, PassEncryptUtil.CannotPerformOperationException, PassEncryptUtil.InvalidHashException, SQLException {
private boolean isAuthorized(String user, String passwordRaw, String target) throws PassEncryptUtil.CannotPerformOperationException, PassEncryptUtil.InvalidHashException, SQLException {
SecurityTable securityTable = plugin.getDB().getSecurityTable();
if (!securityTable.userExists(user)) {

View File

@ -22,10 +22,10 @@ public class PlayersPageResponse extends Response {
}
public static String buildContent(List<UserData> cached) {
StringBuilder html = new StringBuilder();
StringBuilder html = new StringBuilder("<h1>Cached Players</h1><p>");
int size = cached.size();
html.append("<h1>Cached Players</h1><p>")
.append(size)
html.append(size)
.append(" players. Use browser's Search to find players by name. (Chrome Ctrl+F)</p><table><tr>");
cached.sort(new UserDataNameComparator());
int i = 1;
@ -33,10 +33,9 @@ public class PlayersPageResponse extends Response {
String name = userData.getName();
String link = Html.LINK.parse(HtmlUtils.getRelativeInspectUrl(name), name);
html.append("<td>").append(link).append("</td>");
if (i < size) {
if (i % 8 == 0) {
html.append("</tr><tr>");
}
if (i < size
&& i % 8 == 0) {
html.append("</tr><tr>");
}
i++;
}

View File

@ -8,6 +8,13 @@ import main.java.com.djrapitops.plan.Plan;
*/
public class Benchmark {
/**
* Constructor used to hide the public constructor
*/
private Benchmark() {
throw new IllegalStateException("Utility class");
}
/**
* @param source
*/

View File

@ -11,6 +11,13 @@ import main.java.com.djrapitops.plan.Log;
*/
public class Check {
/**
* Constructor used to hide the public constructor
*/
private Check() {
throw new IllegalStateException("Utility class");
}
/**
* If check is false, send message.
*
@ -47,7 +54,7 @@ public class Check {
* @param message Message to send if Condition is false
* @return Condition
*/
public static boolean isTrue_Error(boolean condition, String message) {
public static boolean ErrorIfFalse(boolean condition, String message) {
if (!condition) {
Log.error(message);
Log.toLog(message, Log.getErrorsFilename());

View File

@ -12,6 +12,15 @@ import java.text.DecimalFormat;
*/
public class FormatUtils {
private static DecimalFormat df = new DecimalFormat(Settings.FORMAT_DECIMALS.toString());
/**
* Constructor used to hide the public constructor
*/
private FormatUtils() {
throw new IllegalStateException("Utility class");
}
/**
* @param ms
* @return
@ -170,8 +179,6 @@ public class FormatUtils {
* @return
*/
public static String cutDecimals(double d) {
DecimalFormat df = new DecimalFormat(Settings.FORMAT_DECIMALS.toString());
// df.setRoundingMode(RoundingMode.CEILING);
return df.format(d);
}
}

View File

@ -16,6 +16,13 @@ import java.util.Scanner;
*/
public class HtmlUtils {
/**
* Constructor used to hide the public constructor
*/
private HtmlUtils() {
throw new IllegalStateException("Utility class");
}
/**
* @param fileName
* @return
@ -52,9 +59,13 @@ public class HtmlUtils {
* @return
*/
public static String replacePlaceholders(String html, Map<String, String> replaceMap) {
for (String key : replaceMap.keySet()) {
html = html.replace(key, replaceMap.get(key));
for (Map.Entry<String, String> entrySet : replaceMap.entrySet()) {
String placeholder = entrySet.getKey();
String replacer = entrySet.getValue();
html = html.replace(placeholder, replacer);
}
return html;
}
@ -73,7 +84,7 @@ public class HtmlUtils {
String ip = Plan.getInstance().getVariable().getIp() + ":" + port;
boolean useAlternativeIP = Settings.SHOW_ALTERNATIVE_IP.isTrue();
if (useAlternativeIP) {
ip = Settings.ALTERNATIVE_IP.toString().replace("%port%", "" + port);
ip = Settings.ALTERNATIVE_IP.toString().replace("%port%", String.valueOf(port));
}
return "//" + ip + "/server";
}
@ -95,7 +106,7 @@ public class HtmlUtils {
String ip = Plan.getInstance().getVariable().getIp() + ":" + port;
boolean useAlternativeIP = Settings.SHOW_ALTERNATIVE_IP.isTrue();
if (useAlternativeIP) {
ip = Settings.ALTERNATIVE_IP.toString().replace("%port%", "" + port);
ip = Settings.ALTERNATIVE_IP.toString().replace("%port%", String.valueOf(port));
}
return "//" + ip + "/player/" + playerName;
}
@ -167,7 +178,7 @@ public class HtmlUtils {
public static String swapColorsToSpan(String string) {
Html[] replacer = new Html[]{Html.COLOR_0, Html.COLOR_1, Html.COLOR_2, Html.COLOR_3,
Html.COLOR_4, Html.COLOR_5, Html.COLOR_6, Html.COLOR_7, Html.COLOR_8, Html.COLOR_9,
Html.COLOR_a, Html.COLOR_b, Html.COLOR_c, Html.COLOR_d, Html.COLOR_e, Html.COLOR_f};
Html.COLOR_A, Html.COLOR_B, Html.COLOR_C, Html.COLOR_D, Html.COLOR_E, Html.COLOR_F};
for (Html html : replacer) {
string = string.replace("§" + html.name().charAt(6), html.parse());

View File

@ -18,15 +18,21 @@ import java.util.stream.Collectors;
*/
public class ManageUtils {
/**
* Constructor used to hide the public constructor
*/
private ManageUtils() {
throw new IllegalStateException("Utility class");
}
/**
* Creates a new backup sqlite file with the data of copyFromDB.
*
* @param dbName Name of database (mysql/sqlite)
* @param copyFromDB Database you want to backup.
* @return success?
* @throws java.sql.SQLException
*/
public static boolean backup(String dbName, Database copyFromDB) throws SQLException {
public static boolean backup(String dbName, Database copyFromDB) {
Plan plugin = Plan.getInstance();
String timeStamp = new Date().toString().substring(4, 10).replace(" ", "-");
String fileName = dbName + "-backup-" + timeStamp;

View File

@ -22,6 +22,13 @@ import java.util.stream.Collectors;
*/
public class MiscUtils {
/**
* Constructor used to hide the public constructor
*/
private MiscUtils() {
throw new IllegalStateException("Utility class");
}
/**
* Used to get the current time as milliseconds.
*
@ -56,7 +63,7 @@ public class MiscUtils {
} else if (args.length > 0) {
if (sender.hasPermission(perm.getPermission())) {
playerName = args[0];
} else if (args[0].toLowerCase().equals(sender.getName().toLowerCase())) {
} else if (args[0].equalsIgnoreCase(sender.getName())) {
playerName = sender.getName();
} else {
sender.sendMessage(Phrase.COMMAND_NO_PERMISSION.toString());

View File

@ -10,6 +10,13 @@ import main.java.com.djrapitops.plan.data.UserData;
*/
public class NewPlayerCreator {
/**
* Constructor used to hide the public constructor
*/
private NewPlayerCreator() {
throw new IllegalStateException("Utility class");
}
/**
* Creates a new instance of UserData with default values.
*

View File

@ -17,6 +17,13 @@ import java.security.spec.InvalidKeySpecException;
*/
public class PassEncryptUtil {
/**
* Constructor used to hide the public constructor
*/
private PassEncryptUtil() {
throw new IllegalStateException("Utility class");
}
public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";
// These constants may be changed without breaking existing hashes.
public static final int SALT_BYTE_SIZE = 24;
@ -161,25 +168,25 @@ public class PassEncryptUtil {
}
@SuppressWarnings("serial")
static public class InvalidHashException extends Exception {
public static class InvalidHashException extends Exception {
public InvalidHashException(String message) {
InvalidHashException(String message) {
super(message);
}
public InvalidHashException(String message, Throwable source) {
InvalidHashException(String message, Throwable source) {
super(message, source);
}
}
@SuppressWarnings("serial")
static public class CannotPerformOperationException extends Exception {
public static class CannotPerformOperationException extends Exception {
public CannotPerformOperationException(String message) {
CannotPerformOperationException(String message) {
super(message);
}
public CannotPerformOperationException(String message, Throwable source) {
CannotPerformOperationException(String message, Throwable source) {
super(message, source);
}
}

View File

@ -23,6 +23,13 @@ import java.util.UUID;
*/
public class PlaceholderUtils {
/**
* Constructor used to hide the public constructor
*/
private PlaceholderUtils() {
throw new IllegalStateException("Utility class");
}
/**
* Gets the HashMap that is used to replace placeholders in Analysis.
*
@ -94,19 +101,19 @@ public class PlaceholderUtils {
replaceMap.put("%banned%", data.isBanned() ? Html.BANNED.parse() : "");
replaceMap.put("%op%", data.isOp() ? Html.OPERATOR.parse() : "");
replaceMap.put("%isonline%", (data.isOnline()) ? Html.ONLINE.parse() : Html.OFFLINE.parse());
replaceMap.put("%deaths%", data.getDeaths() + "");
replaceMap.put("%playerkills%", data.getPlayerKills().size() + "");
replaceMap.put("%mobkills%", data.getMobKills() + "");
replaceMap.put("%deaths%", String.valueOf(data.getDeaths()));
replaceMap.put("%playerkills%", String.valueOf(data.getPlayerKills().size()));
replaceMap.put("%mobkills%", String.valueOf(data.getMobKills()));
replaceMap.put("%sessionaverage%", FormatUtils.formatTimeAmount(MathUtils.averageLong(AnalysisUtils.transformSessionDataToLengths(data.getSessions()))));
replaceMap.put("%killstable%", KillsTableCreator.createKillsTable(data.getPlayerKills()));
Plan plugin = Plan.getInstance();
replaceMap.put("%version%", plugin.getDescription().getVersion());
replaceMap.put("%planlite%", "");
replaceMap.put("%graphmaxplayers%", 2 + "");
replaceMap.put("%graphmaxplayers%", "2");
String scatterGraphData = PlayerActivityGraphCreator.buildScatterDataStringSessions(data.getSessions(), TimeAmount.WEEK.ms());
replaceMap.put("%dataweek%", scatterGraphData);
replaceMap.put("%playersgraphcolor%", Settings.HCOLOR_ACT_ONL + "");
replaceMap.put("%playersgraphfill%", Settings.HCOLOR_ACT_ONL_FILL + "");
replaceMap.put("%playersgraphcolor%", Settings.HCOLOR_ACT_ONL.toString());
replaceMap.put("%playersgraphfill%", Settings.HCOLOR_ACT_ONL_FILL.toString());
replaceMap.put("%datapunchcard%", PunchCardGraphCreator.generateDataArray(data.getSessions()));
String[] distribution = SessionLengthDistributionGraphCreator.generateDataArraySessions(data.getSessions());
replaceMap.put("%datasessiondistribution%", distribution[0]);
@ -119,8 +126,8 @@ public class PlaceholderUtils {
replaceMap.put("#" + defaultCols[i], "#" + colors[i]);
}
}
replaceMap.put("%refreshlong%", plugin.getInspectCache().getCacheTime(uuid) + "");
replaceMap.put("%currenttime%", MiscUtils.getTime() + "");
replaceMap.put("%refreshlong%", String.valueOf(plugin.getInspectCache().getCacheTime(uuid)));
replaceMap.put("%currenttime%", String.valueOf(MiscUtils.getTime()));
replaceMap.put("%servername%", Settings.SERVER_NAME.toString());
String pluginsTabHtml = plugin.getHookHandler().getPluginsTabLayoutForInspect();
Map<String, String> additionalReplaceRules = plugin.getHookHandler().getAdditionalInspectReplaceRules(uuid);

View File

@ -130,7 +130,7 @@ public class Analysis {
Benchmark.start("Analysis Phase");
plugin.processStatus().setStatus("Analysis", "Analysis Phase");
log(Phrase.ANALYSIS_BEGIN_ANALYSIS.parse(rawData.size() + "", fetchPhaseLength + ""));
log(Phrase.ANALYSIS_BEGIN_ANALYSIS.parse(String.valueOf(rawData.size()), String.valueOf(fetchPhaseLength)));
String playersTable = PlayersTableCreator.createSortablePlayersTable(rawData);
analysisData.setPlayersTable(playersTable);
@ -146,11 +146,12 @@ public class Analysis {
analysisCache.cache(analysisData);
long time = plugin.processStatus().finishExecution("Analysis");
if (Settings.ANALYSIS_LOG_FINISHED.isTrue()) {
Log.info(Phrase.ANALYSIS_COMPLETE.parse(time + "", HtmlUtils.getServerAnalysisUrlWithProtocol()));
Log.info(Phrase.ANALYSIS_COMPLETE.parse(String.valueOf(time), HtmlUtils.getServerAnalysisUrlWithProtocol()));
}
ExportUtility.export(plugin, analysisData, rawData);
} catch (Throwable e) {
} catch (Exception e) {
Log.toLog(this.getClass().getName(), e);
plugin.processStatus().setStatus("Analysis", "Error: " + e);
return false;
@ -207,7 +208,7 @@ public class Analysis {
if (analysisTypes.contains(boolTot)) {
replaceMap.put(source.getPlaceholder(boolTot.getPlaceholderModifier()), AnalysisUtils.getBooleanTotal(boolTot, source, uuids));
}
} catch (Throwable e) {
} catch (Exception e) {
Log.error("A PluginData-source caused an exception: " + source.getPlaceholder("").replace("%", ""));
Log.toLog(this.getClass().getName(), e);
@ -247,7 +248,7 @@ public class Analysis {
long now = MiscUtils.getTime();
Benchmark.start("Analysis: Fill Dataset");
rawData.forEach((uData) -> {
rawData.forEach(uData -> {
uData.access();
Map<String, Long> gmTimes = uData.getGmTimes();
String[] gms = new String[]{"SURVIVAL", "CREATIVE", "ADVENTURE", "SPECTATOR"};

View File

@ -18,6 +18,13 @@ import java.util.stream.Stream;
*/
public class AnalysisUtils {
/**
* Constructor used to hide the public constructor
*/
private AnalysisUtils() {
throw new IllegalStateException("Utility class");
}
/**
* @param now
* @param lastPlayed
@ -27,18 +34,16 @@ public class AnalysisUtils {
*/
public static boolean isActive(long now, long lastPlayed, long playTime, int loginTimes) {
int timeToActive = Settings.ANALYSIS_MINUTES_FOR_ACTIVE.getNumber();
if (timeToActive < 0) {
timeToActive = 0;
}
long twoWeeks = 1209600000;
if (now - lastPlayed < twoWeeks) {
if (loginTimes > 3) {
if (playTime > 60 * timeToActive) {
return true;
}
}
}
return false;
return now - lastPlayed < twoWeeks
&& loginTimes > 3
&& playTime > 60 * timeToActive;
}
/**
@ -99,8 +104,8 @@ public class AnalysisUtils {
default:
return source.parseContainer("", "Wrong Analysistype specified: " + analysisType.name());
}
return source.parseContainer(analysisType.getModifier(), total + "");
} catch (Throwable e) {
return source.parseContainer(analysisType.getModifier(), String.valueOf(total));
} catch (Exception e) {
return logPluginDataCausedError(source, e);
}
}
@ -131,7 +136,7 @@ public class AnalysisUtils {
return source.parseContainer(analysisType.getModifier(), FormatUtils.formatTimeAmount((long) average));
case LONG_AVG:
long averageLong = MathUtils.averageLong(getCorrectValues(uuids, source).map(i -> (Long) i));
return source.parseContainer(analysisType.getModifier(), averageLong + "");
return source.parseContainer(analysisType.getModifier(), String.valueOf(averageLong));
case LONG_TIME_MS_AVG:
average = MathUtils.averageLong(getCorrectValues(uuids, source).map(i -> (Long) i));
return source.parseContainer(analysisType.getModifier(), FormatUtils.formatTimeAmount((long) average));
@ -145,7 +150,7 @@ public class AnalysisUtils {
return source.parseContainer("Err ", "Wrong Analysistype specified: " + analysisType.name());
}
return source.parseContainer(analysisType.getModifier(), FormatUtils.cutDecimals(average));
} catch (Throwable e) {
} catch (Exception e) {
return logPluginDataCausedError(source, e);
}
}
@ -164,7 +169,7 @@ public class AnalysisUtils {
.collect(Collectors.toList());
long count = tempList.stream().filter(value -> value).count();
return source.parseContainer(analysisType.getModifier(), ((double) (count / tempList.size()) * 100) + "%");
} catch (Throwable e) {
} catch (Exception e) {
return logPluginDataCausedError(source, e);
}
}
@ -185,7 +190,7 @@ public class AnalysisUtils {
.collect(Collectors.toList());
long count = tempList.stream().filter(value -> value).count();
return source.parseContainer(analysisType.getModifier(), count + " / " + tempList.size());
} catch (Throwable e) {
} catch (Exception e) {
return logPluginDataCausedError(source, e);
}
}
@ -210,15 +215,12 @@ public class AnalysisUtils {
long now = MiscUtils.getTime();
long nowMinusScale = now - scale;
Set<UUID> uniqueJoins = new HashSet<>();
sessions.keySet().forEach((uuid) -> {
List<SessionData> s = sessions.get(uuid);
for (SessionData session : s) {
if (session.getSessionStart() < nowMinusScale) {
continue;
}
uniqueJoins.add(uuid);
}
});
sessions.forEach((uuid, s) ->
s.stream()
.filter(session -> session.getSessionStart() >= nowMinusScale)
.map(session -> uuid)
.forEach(uniqueJoins::add)
);
return uniqueJoins.size();
}
@ -231,13 +233,12 @@ public class AnalysisUtils {
Map<Integer, Set<UUID>> uniqueJoins = new HashMap<>();
long now = MiscUtils.getTime();
long nowMinusScale = now - scale;
sessions.keySet().forEach((uuid) -> {
List<SessionData> s = sessions.get(uuid);
sessions.forEach((uuid, s) -> {
for (SessionData session : s) {
if (scale != -1) {
if (session.getSessionStart() < nowMinusScale) {
continue;
}
if (scale != -1
&& session.getSessionStart() < nowMinusScale) {
continue;
}
int day = getDayOfYear(session);
@ -246,11 +247,14 @@ public class AnalysisUtils {
uniqueJoins.get(day).add(uuid);
}
});
int total = MathUtils.sumInt(uniqueJoins.values().stream().map(Set::size));
int numberOfDays = uniqueJoins.keySet().size();
int numberOfDays = uniqueJoins.size();
if (numberOfDays == 0) {
return 0;
}
return total / numberOfDays;
}
@ -268,8 +272,10 @@ public class AnalysisUtils {
days.add(day);
}
}
long total = registers.stream().filter(date -> date >= nowMinusScale).count();
int numberOfDays = days.size();
if (numberOfDays == 0) {
return 0;
}

View File

@ -13,11 +13,18 @@ import java.util.List;
*/
public class DouglasPeuckerAlgorithm {
/**
* Constructor used to hide the public constructor
*/
private DouglasPeuckerAlgorithm() {
throw new IllegalStateException("Utility class");
}
public static List<Point> reducePoints(List<Point> points, double epsilon) {
if (points.isEmpty()) {
return points;
}
if (epsilon == -1) {
if (Double.compare(epsilon, -1) == 0) {
epsilon = 0.002;
}
int size = points.size();

View File

@ -22,6 +22,13 @@ import java.util.List;
*/
public class ExportUtility {
/**
* Constructor used to hide the public constructor
*/
private ExportUtility() {
throw new IllegalStateException("Utility class");
}
/**
* @return
*/
@ -29,10 +36,9 @@ public class ExportUtility {
String path = Settings.ANALYSIS_EXPORT_PATH.toString();
if (path.contains(":")) {
File folder = new File(path);
if (folder.exists()) {
if (folder.isDirectory()) {
return folder;
}
if (folder.exists()
&& folder.isDirectory()) {
return folder;
}
folder.mkdirs();
return folder;

View File

@ -55,7 +55,6 @@ public class Line {
public double getPerpendicularDistance(Point from) {
double a = getA();
double b = -1;
double x = from.getX();
double y = from.getY();
return Math.abs(a * x - y + c) / Math.sqrt(Math.pow(a, 2) + 1);

View File

@ -11,6 +11,13 @@ import java.util.stream.Stream;
*/
public class MathUtils {
/**
* Constructor used to hide the public constructor
*/
private MathUtils() {
throw new IllegalStateException("Utility class");
}
private static final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
private static final DecimalFormat decimalFormat = new DecimalFormat("#.##", decimalFormatSymbols);

View File

@ -10,6 +10,13 @@ import java.util.Map;
*/
public class MapComparator {
/**
* Constructor used to hide the public constructor
*/
private MapComparator() {
throw new IllegalStateException("Utility class");
}
/**
* Sorts a HashMap of String, Integer by the Values of the HashMap.
*
@ -19,7 +26,7 @@ public class MapComparator {
*/
public static List<String[]> sortByValue(Map<String, Integer> hashMap) {
List<String[]> sortedList = new ArrayList<>();
hashMap.keySet().forEach((key) -> sortedList.add(new String[]{"" + hashMap.get(key), key}));
hashMap.keySet().forEach(key -> sortedList.add(new String[]{String.valueOf(hashMap.get(key)), key}));
sortedList.sort(Comparator.comparingInt(strings -> Integer.parseInt(strings[0])));
return sortedList;
}
@ -30,7 +37,7 @@ public class MapComparator {
*/
public static List<String[]> sortByValueLong(Map<String, Long> hashMap) {
List<String[]> sortedList = new ArrayList<>();
hashMap.keySet().forEach((key) -> sortedList.add(new String[]{"" + hashMap.get(key), key}));
hashMap.keySet().forEach(key -> sortedList.add(new String[]{String.valueOf(hashMap.get(key)), key}));
sortedList.sort(Comparator.comparing(strings -> Long.valueOf(strings[0])));
return sortedList;
}

View File

@ -351,9 +351,9 @@ public class Metrics {
return null;
}
chart.put("data", data);
} catch (Throwable t) {
} catch (Exception e) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, e);
}
return null;
}

View File

@ -18,6 +18,13 @@ import java.util.UUID;
*/
public class UUIDUtility {
/**
* Constructor used to hide the public constructor
*/
private UUIDUtility() {
throw new IllegalStateException("Utility class");
}
/**
* @param playername
* @return

View File

@ -30,7 +30,7 @@ public class PhraseTest {
*/
@Before
public void setUp() throws Exception {
TestInit t = TestInit.init();
TestInit.init();
}
/**
@ -49,7 +49,7 @@ public class PhraseTest {
*
*/
@Test
public void testParse_0args() {
public void testParseWithZeroArgs() {
Phrase instance = Phrase.DEM_UNKNOWN;
String expResult = "Not Known";
String result = instance.parse();
@ -60,7 +60,7 @@ public class PhraseTest {
*
*/
@Test
public void testParse_StringArr() {
public void testParseStringArr() {
Phrase instance = Phrase.REPLACE0;
String expResult = "Test";
String result = instance.parse(expResult);

View File

@ -38,7 +38,7 @@ public class SettingsTest {
*/
@Before
public void setUp() throws Exception {
TestInit t = TestInit.init();
TestInit.init();
}
/**

View File

@ -74,7 +74,7 @@ public class DataCacheHandlerTest {
}
@Override
public HashMap<String, Integer> getCommandUse() {
public Map<String, Integer> getCommandUse() {
return new HashMap<>();
}

View File

@ -41,7 +41,7 @@ public class SessionCacheTest {
*/
@Before
public void setUp() throws Exception {
TestInit t = TestInit.init();
TestInit.init();
test = new SessionCache();
}

View File

@ -50,7 +50,7 @@ public class DataCacheProcessQueueTest {
*/
@Before
public void setUp() throws Exception {
TestInit t = TestInit.init();
TestInit.init();
handler = new DataCacheHandler(Plan.getInstance()) {
@Override
public boolean getCommandUseFromDb() {

View File

@ -63,7 +63,6 @@ public class DataCacheSaveQueueTest {
calledSaveUserData2 = true;
}
calledSaveUserData = true;
}
};
when(plan.getDB()).thenReturn(db);

View File

@ -36,7 +36,7 @@ public class ChatHandlingTest {
*/
@Before
public void setUp() throws Exception {
TestInit t = TestInit.init();
TestInit.init();
}
/**
@ -46,7 +46,7 @@ public class ChatHandlingTest {
public void testProcessChatInfoAddedNickname() {
UserData data = MockUtils.mockUser2();
String expected = "TestNicknameChatHandling";
ChatHandling.processChatInfo(data, expected, "");
ChatHandling.processChatInfo(data, expected);
assertTrue("Didn't add nickname", data.getNicknames().contains(expected));
}
}

View File

@ -37,7 +37,7 @@ public class KickInfoTest {
*/
@Before
public void setUp() throws Exception {
TestInit t = TestInit.init();
TestInit.init();
}
/**

View File

@ -43,7 +43,6 @@ public class LogoutInfoTest {
data.setLastPlayed(10L);
data.updateBanned(false);
long time = 20L;
Exception ex = null;
data.setLastGamemode("SURVIVAL");
LogoutInfo i = new LogoutInfo(data.getUuid(), time, true, Gamemode.CREATIVE, new SessionData(0, 1));
assertTrue(i.process(data));

View File

@ -26,7 +26,7 @@ public class HtmlTest {
*
*/
@Test
public void testParse_0args() {
public void testParseWithZeroArgs() {
Html instance = Html.REPLACE0;
String expResult = "REPLACE0";
String result = instance.parse();
@ -37,7 +37,7 @@ public class HtmlTest {
*
*/
@Test
public void testParse_StringArr() {
public void testParseStringArr() {
Html instance = Html.REPLACE0;
String expResult = "Test";
String result = instance.parse(expResult);

View File

@ -42,7 +42,7 @@ public class FormatUtilsTest {
*/
@Test
public void testFormatTimeAmount() throws Exception {
TestInit t = TestInit.init();
TestInit.init();
long second = 1000L;
String expResult = "1s";
String result = FormatUtils.formatTimeAmount(second);

View File

@ -45,7 +45,7 @@ public class HtmlUtilsTest {
*/
@Test
public void testGetHtmlStringFromResource() throws Exception {
TestInit t = TestInit.init();
TestInit.init();
String fileName = "player.html";
String result = HtmlUtils.getStringFromResource(fileName);
assertTrue("Result empty", !result.isEmpty());

View File

@ -43,7 +43,7 @@ public class ManageUtilsTest {
*/
@Before
public void setUp() throws Exception {
TestInit t = TestInit.init();
TestInit.init();
}
/**

View File

@ -40,7 +40,7 @@ public class AnalysisUtilsTest {
*/
@Before
public void setUp() throws Exception {
TestInit t = TestInit.init();
TestInit.init();
}
/**

View File

@ -38,7 +38,7 @@ public class MathUtilsTest {
l.add(5);
l.add(15);
double result = MathUtils.averageInt(l.stream());
assertTrue(exp == result);
assertTrue(Double.compare(exp, result) == 0);
}
/**
@ -49,7 +49,7 @@ public class MathUtilsTest {
List<Integer> l = new ArrayList<>();
double exp = 0;
double result = MathUtils.averageInt(l.stream());
assertTrue(result + "/" + exp, exp == result);
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
@ -64,7 +64,7 @@ public class MathUtilsTest {
l.add(5L);
l.add(15L);
double result = MathUtils.averageLong(l);
assertTrue(result + "/" + exp, exp == result);
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
@ -79,7 +79,7 @@ public class MathUtilsTest {
l.add(4.5);
l.add(15.0);
double result = MathUtils.averageDouble(l.stream());
assertTrue(result + "/" + exp, exp == result);
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
@ -90,7 +90,7 @@ public class MathUtilsTest {
public void testAverage() {
double exp = 10;
double result = MathUtils.average(40, 4);
assertTrue(result + "/" + exp, exp == result);
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
@ -107,7 +107,7 @@ public class MathUtilsTest {
l.add(false);
}
long result = MathUtils.countTrueBoolean(l.stream());
assertTrue(result + "/" + exp, exp == result);
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
@ -122,7 +122,7 @@ public class MathUtilsTest {
l.add(5);
l.add(15);
double result = MathUtils.sumInt(l.stream());
assertTrue(result + "/" + exp, exp == result);
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
@ -137,7 +137,7 @@ public class MathUtilsTest {
l.add(5L);
l.add(15L);
long result = MathUtils.sumLong(l.stream());
assertTrue(result + "/" + exp, exp == result);
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
@ -152,6 +152,6 @@ public class MathUtilsTest {
l.add(45.0);
l.add(5.0531541);
double result = MathUtils.sumDouble(l.stream());
assertTrue(result + "/" + exp, exp == result);
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
}