Replace remaining references to PlotSquared#log

This commit is contained in:
Alexander Söderberg 2020-07-06 17:17:46 +02:00
parent 1c254984c1
commit 298e65a394
No known key found for this signature in database
GPG Key ID: C0207FF7EA146678
16 changed files with 298 additions and 379 deletions

View File

@ -95,6 +95,8 @@ import org.bukkit.entity.Vehicle;
import org.bukkit.entity.WaterMob; import org.bukkit.entity.WaterMob;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -110,6 +112,8 @@ import java.util.stream.Stream;
@SuppressWarnings({"unused", "WeakerAccess"}) @SuppressWarnings({"unused", "WeakerAccess"})
public class BukkitUtil extends WorldUtil { public class BukkitUtil extends WorldUtil {
private static final Logger logger = LoggerFactory.getLogger(BukkitUtil.class);
private static String lastString = null; private static String lastString = null;
private static World lastWorld = null; private static World lastWorld = null;
@ -505,7 +509,7 @@ public class BukkitUtil extends WorldUtil {
@NonNull final BiomeType biomeType) { @NonNull final BiomeType biomeType) {
final World world = getWorld(worldName); final World world = getWorld(worldName);
if (world == null) { if (world == null) {
PlotSquared.log("An error occurred setting the biome because the world was null."); logger.warn("An error occured while setting the biome because the world was null", new RuntimeException());
return; return;
} }
final Biome biome = BukkitAdapter.adapt(biomeType); final Biome biome = BukkitAdapter.adapt(biomeType);
@ -619,7 +623,7 @@ public class BukkitUtil extends WorldUtil {
} }
break; break;
default: { default: {
PlotSquared.log(Captions.PREFIX + "Unknown entity category requested: " + category); logger.error("Unknown entity category requested: {}", category);
} }
break; break;
} }

View File

@ -30,12 +30,13 @@ import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
import com.plotsquared.core.PlotSquared; import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.PlotVersion; import com.plotsquared.core.PlotVersion;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.configuration.Settings;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
import java.io.IOException; import java.io.IOException;
@ -44,6 +45,8 @@ import java.net.URL;
public class UpdateUtility implements Listener { public class UpdateUtility implements Listener {
private static final Logger logger = LoggerFactory.getLogger(UpdateUtility.class);
public static PlotVersion internalVersion; public static PlotVersion internalVersion;
public static String spigotVersion; public static String spigotVersion;
public static boolean hasUpdate; public static boolean hasUpdate;
@ -68,26 +71,22 @@ public class UpdateUtility implements Listener {
.getAsJsonObject(); .getAsJsonObject();
spigotVersion = result.get("current_version").getAsString(); spigotVersion = result.get("current_version").getAsString();
} catch (IOException e) { } catch (IOException e) {
PlotSquared.log(Captions.PREFIX + "&cUnable to check for updates because: " + e); logger.error("Unable to check for updates. Error: {}", e.getMessage());
return; return;
} }
if (internalVersion.isLaterVersion(spigotVersion)) { if (internalVersion.isLaterVersion(spigotVersion)) {
PlotSquared logger.info("There appears to be a PlotSquared update available!");
.log(Captions.PREFIX + "&6There appears to be a PlotSquared update available!"); logger.info("You are running version {}, the latest version is {}",
PlotSquared.log( internalVersion.versionString(), spigotVersion);
Captions.PREFIX + "&6You are running version " + internalVersion.versionString() logger.info("https://www.spigotmc.org/resources/77506/updates");
+ ", &6latest version is " + spigotVersion);
PlotSquared
.log(Captions.PREFIX + "&6https://www.spigotmc.org/resources/77506/updates");
hasUpdate = true; hasUpdate = true;
if (Settings.UpdateChecker.NOTIFY_ONCE) { if (Settings.UpdateChecker.NOTIFY_ONCE) {
cancelTask(); cancelTask();
} }
} else if (notify) { } else if (notify) {
notify = false; notify = false;
PlotSquared.log(Captions.PREFIX logger.info("Congratulations! You are running the latest PlotSquared version");
+ "Congratulations! You are running the latest PlotSquared version.");
} }
}, 0L, Settings.UpdateChecker.POLL_RATE * 60 * 20); }, 0L, Settings.UpdateChecker.POLL_RATE * 60 * 20);
} }

View File

@ -28,7 +28,6 @@ package com.plotsquared.core;
import com.plotsquared.core.command.WE_Anywhere; import com.plotsquared.core.command.WE_Anywhere;
import com.plotsquared.core.components.ComponentPresetManager; import com.plotsquared.core.components.ComponentPresetManager;
import com.plotsquared.core.configuration.Caption; import com.plotsquared.core.configuration.Caption;
import com.plotsquared.core.configuration.CaptionUtility;
import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.ConfigurationSection; import com.plotsquared.core.configuration.ConfigurationSection;
import com.plotsquared.core.configuration.ConfigurationUtil; import com.plotsquared.core.configuration.ConfigurationUtil;
@ -48,7 +47,6 @@ import com.plotsquared.core.generator.HybridUtils;
import com.plotsquared.core.generator.IndependentPlotGenerator; import com.plotsquared.core.generator.IndependentPlotGenerator;
import com.plotsquared.core.listener.WESubscriber; import com.plotsquared.core.listener.WESubscriber;
import com.plotsquared.core.location.Location; import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.ConsolePlayer;
import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.BlockBucket; import com.plotsquared.core.plot.BlockBucket;
import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.Plot;
@ -81,7 +79,6 @@ import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.SetupUtils; import com.plotsquared.core.util.SetupUtils;
import com.plotsquared.core.util.StringMan; import com.plotsquared.core.util.StringMan;
import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.logger.ILogger;
import com.plotsquared.core.util.query.PlotQuery; import com.plotsquared.core.util.query.PlotQuery;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import com.plotsquared.core.uuid.UUIDPipeline; import com.plotsquared.core.uuid.UUIDPipeline;
@ -90,9 +87,10 @@ import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
import lombok.Setter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
@ -138,6 +136,8 @@ import java.util.zip.ZipInputStream;
*/ */
@SuppressWarnings({"unused", "WeakerAccess"}) @SuppressWarnings({"unused", "WeakerAccess"})
public class PlotSquared { public class PlotSquared {
private static final Logger logger = LoggerFactory.getLogger(PlotSquared.class);
private static final Set<Plot> EMPTY_SET = Collections.unmodifiableSet(Collections.emptySet()); private static final Set<Plot> EMPTY_SET = Collections.unmodifiableSet(Collections.emptySet());
private static PlotSquared instance; private static PlotSquared instance;
// Implementation // Implementation
@ -164,8 +164,6 @@ public class PlotSquared {
public HashMap<String, Set<PlotCluster>> clusters_tmp; public HashMap<String, Set<PlotCluster>> clusters_tmp;
public HashMap<String, HashMap<PlotId, Plot>> plots_tmp; public HashMap<String, HashMap<PlotId, Plot>> plots_tmp;
private YamlConfiguration config; private YamlConfiguration config;
// Implementation logger
@Deprecated @Setter @Getter private ILogger logger;
// Platform / Version / Update URL // Platform / Version / Update URL
private PlotVersion version; private PlotVersion version;
// Files and configuration // Files and configuration
@ -188,7 +186,6 @@ public class PlotSquared {
this.thread = Thread.currentThread(); this.thread = Thread.currentThread();
this.IMP = iPlotMain; this.IMP = iPlotMain;
this.logger = iPlotMain;
Settings.PLATFORM = platform; Settings.PLATFORM = platform;
// //
@ -240,7 +237,7 @@ public class PlotSquared {
if (!getConfigurationVersion().equalsIgnoreCase("v5")) { if (!getConfigurationVersion().equalsIgnoreCase("v5")) {
// Perform upgrade // Perform upgrade
if (DBFunc.dbManager.convertFlags()) { if (DBFunc.dbManager.convertFlags()) {
log(Captions.PREFIX.getTranslated() + "Flags were converted successfully!"); logger.info("Flags were converted successfully");
// Update the config version // Update the config version
setConfigurationVersion("v5"); setConfigurationVersion("v5");
} }
@ -288,8 +285,7 @@ public class PlotSquared {
if (Settings.Enabled_Components.WORLDEDIT_RESTRICTIONS) { if (Settings.Enabled_Components.WORLDEDIT_RESTRICTIONS) {
try { try {
if (this.IMP.initWorldEdit()) { if (this.IMP.initWorldEdit()) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "&6" + IMP.getPluginName() logger.info("{} hooked into WorldEdit", imp().getPluginName());
+ " hooked into WorldEdit.");
this.worldedit = WorldEdit.getInstance(); this.worldedit = WorldEdit.getInstance();
WorldEdit.getInstance().getEventBus().register(new WESubscriber()); WorldEdit.getInstance().getEventBus().register(new WESubscriber());
if (Settings.Enabled_Components.COMMANDS) { if (Settings.Enabled_Components.COMMANDS) {
@ -298,8 +294,8 @@ public class PlotSquared {
} }
} catch (Throwable e) { } catch (Throwable e) {
PlotSquared.debug( logger.error("Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master");
"Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master");
} }
} }
// Economy // Economy
@ -312,8 +308,7 @@ public class PlotSquared {
try { try {
new ComponentPresetManager(); new ComponentPresetManager();
} catch (final Exception e) { } catch (final Exception e) {
PlotSquared.log(Captions.PREFIX + "Failed to initialize the preset system"); logger.error("Failed to initialize the preset system", e);
e.printStackTrace();
} }
} }
@ -334,14 +329,11 @@ public class PlotSquared {
continue; continue;
} }
if (!WorldUtil.IMP.isWorld(world) && !world.equals("*")) { if (!WorldUtil.IMP.isWorld(world) && !world.equals("*")) {
debug("`" + world + "` was not properly loaded - " + IMP.getPluginName() logger.debug("`{}` was not properly loaded - {} will now try to load it properly",
+ " will now try to load it properly: "); world, imp().getPluginName());
debug( logger.debug(" - Are you trying to delete this world? Remember to remove it from the worlds.yml, bukkit.yml and multiverse worlds.yml");
" - Are you trying to delete this world? Remember to remove it from the worlds.yml, bukkit.yml and multiverse worlds.yml"); logger.debug(" - Your world management plugin may be faulty (or non existent)");
debug( logger.debug(" This message may also be a false positive and could be ignored.");
" - Your world management plugin may be faulty (or non existent)");
debug(
" This message may also be a false positive and could be ignored.");
PlotSquared.this.IMP.setGenerator(world); PlotSquared.this.IMP.setGenerator(world);
} }
} }
@ -372,9 +364,7 @@ public class PlotSquared {
e.printStackTrace(); e.printStackTrace();
} }
PlotSquared.log(Captions.PREFIX + CaptionUtility logger.debug("{} is now enabled!", imp().getPluginName());
.format(ConsolePlayer.getConsole(), Captions.ENABLED.getTranslated(),
IMP.getPluginName()));
} }
/** /**
@ -406,11 +396,7 @@ public class PlotSquared {
message.toString().isEmpty())) { message.toString().isEmpty())) {
return; return;
} }
if (PlotSquared.get() == null || PlotSquared.get().getLogger() == null) { logger.info(StringMan.getString(message));
System.out.printf("[P2][Info] %s\n", StringMan.getString(message));
} else {
PlotSquared.get().getLogger().log(StringMan.getString(message));
}
} }
/** /**
@ -422,11 +408,7 @@ public class PlotSquared {
*/ */
@Deprecated public static void debug(@Nullable Object message) { @Deprecated public static void debug(@Nullable Object message) {
if (Settings.DEBUG) { if (Settings.DEBUG) {
if (PlotSquared.get() == null || PlotSquared.get().getLogger() == null) { logger.debug(StringMan.getString(message));
System.out.printf("[P2][Debug] %s\n", StringMan.getString(message));
} else {
PlotSquared.get().getLogger().log(StringMan.getString(message));
}
} }
} }
@ -557,21 +539,16 @@ public class PlotSquared {
regionInts.forEach(l -> regions.add(BlockVector2.at(l[0], l[1]))); regionInts.forEach(l -> regions.add(BlockVector2.at(l[0], l[1])));
chunkInts.forEach(l -> chunks.add(BlockVector2.at(l[0], l[1]))); chunkInts.forEach(l -> chunks.add(BlockVector2.at(l[0], l[1])));
int height = (int) list.get(2); int height = (int) list.get(2);
PlotSquared.log( logger.info("Incomplete road regeneration found. Restarting in world {} with height {}", plotArea.getWorldName(), height);
Captions.PREFIX + "Incomplete road regeneration found. Restarting in world "
+ plotArea.getWorldName() + " with height " + height + ".");
PlotSquared.debug(" Regions: " + regions.size()); PlotSquared.debug(" Regions: " + regions.size());
PlotSquared.debug(" Chunks: " + chunks.size()); PlotSquared.debug(" Chunks: " + chunks.size());
HybridUtils.UPDATE = true; HybridUtils.UPDATE = true;
HybridUtils.manager.scheduleRoadUpdate(plotArea, regions, height, chunks); HybridUtils.manager.scheduleRoadUpdate(plotArea, regions, height, chunks);
} catch (IOException | ClassNotFoundException e) { } catch (IOException | ClassNotFoundException e) {
PlotSquared.log(Captions.PREFIX + "Error restarting road regeneration."); logger.error("Error restarting road regeneration", e);
e.printStackTrace();
} finally { } finally {
if (!file.delete()) { if (!file.delete()) {
PlotSquared.log( logger.error("Error deleting persistent_regen_data_{}. Please delete this file manually", plotArea.getId());
Captions.PREFIX + "Error deleting persistent_regen_data_" + plotArea.getId()
+ ". Please manually delete this file.");
} }
} }
}); });
@ -1159,12 +1136,10 @@ public class PlotSquared {
// Conventional plot generator // Conventional plot generator
PlotArea plotArea = plotGenerator.getNewPlotArea(world, null, null, null); PlotArea plotArea = plotGenerator.getNewPlotArea(world, null, null, null);
PlotManager plotManager = plotArea.getPlotManager(); PlotManager plotManager = plotArea.getPlotManager();
PlotSquared.log(Captions.PREFIX + "&aDetected world load for '" + world + "'"); logger.info("Detected world load for '{}'", world);
PlotSquared logger.info(" - generator: {}>{}", baseGenerator, plotGenerator);
.log(Captions.PREFIX + "&3 - generator: &7" + baseGenerator + ">" + plotGenerator); logger.info(" - plot world: {}", plotArea.getClass().getCanonicalName());
PlotSquared.log(Captions.PREFIX + "&3 - plotworld: &7" + plotArea.getClass().getName()); logger.info("- plot area manager: {}", plotManager.getClass().getCanonicalName());
PlotSquared.log(
Captions.PREFIX + "&3 - plotAreaManager: &7" + plotManager.getClass().getName());
if (!this.worlds.contains(path)) { if (!this.worlds.contains(path)) {
this.worlds.createSection(path); this.worlds.createSection(path);
worldSection = this.worlds.getConfigurationSection(path); worldSection = this.worlds.getConfigurationSection(path);
@ -1186,10 +1161,10 @@ public class PlotSquared {
ConfigurationSection areasSection = worldSection.getConfigurationSection("areas"); ConfigurationSection areasSection = worldSection.getConfigurationSection("areas");
if (areasSection == null) { if (areasSection == null) {
if (plotAreaManager.getPlotAreas(world, null).length != 0) { if (plotAreaManager.getPlotAreas(world, null).length != 0) {
debug("World possibly already loaded: " + world); logger.debug("World possibly already loaded: {}", world);
return; return;
} }
PlotSquared.log(Captions.PREFIX + "&aDetected world load for '" + world + "'"); logger.info("Detected world load for '{}'", world);
String gen_string = worldSection.getString("generator.plugin", IMP.getPluginName()); String gen_string = worldSection.getString("generator.plugin", IMP.getPluginName());
if (type == PlotAreaType.PARTIAL) { if (type == PlotAreaType.PARTIAL) {
Set<PlotCluster> clusters = Set<PlotCluster> clusters =
@ -1205,8 +1180,7 @@ public class PlotSquared {
String fullId = name + "-" + pos1 + "-" + pos2; String fullId = name + "-" + pos1 + "-" + pos2;
worldSection.createSection("areas." + fullId); worldSection.createSection("areas." + fullId);
DBFunc.replaceWorld(world, world + ";" + name, pos1, pos2); // NPE DBFunc.replaceWorld(world, world + ";" + name, pos1, pos2); // NPE
logger.info(" - {}-{}-{}", name, pos1, pos2);
PlotSquared.log(Captions.PREFIX + "&3 - " + name + "-" + pos1 + "-" + pos2);
GeneratorWrapper<?> areaGen = this.IMP.getGenerator(world, gen_string); GeneratorWrapper<?> areaGen = this.IMP.getGenerator(world, gen_string);
if (areaGen == null) { if (areaGen == null) {
throw new IllegalArgumentException("Invalid Generator: " + gen_string); throw new IllegalArgumentException("Invalid Generator: " + gen_string);
@ -1220,14 +1194,10 @@ public class PlotSquared {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
PlotSquared.log( logger.info(" | generator: {}>{}", baseGenerator, areaGen);
Captions.PREFIX + "&c | &9generator: &7" + baseGenerator + ">" logger.info(" | plot world: {}", pa);
+ areaGen); logger.info(" | manager: {}", pa);
PlotSquared.log(Captions.PREFIX + "&c | &9plotworld: &7" + pa); logger.info("Note: Area created for cluster '{}' (invalid or old configuration?)", name);
PlotSquared.log(Captions.PREFIX + "&c | &9manager: &7" + pa);
PlotSquared.log(
Captions.PREFIX + "&cNote: &7Area created for cluster:" + name
+ " (invalid or old configuration?)");
areaGen.getPlotGenerator().initialize(pa); areaGen.getPlotGenerator().initialize(pa);
areaGen.augment(pa); areaGen.augment(pa);
toLoad.add(pa); toLoad.add(pa);
@ -1249,10 +1219,9 @@ public class PlotSquared {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
PlotSquared logger.info(" - generator: {}>{}", baseGenerator, areaGen);
.log(Captions.PREFIX + "&3 - generator: &7" + baseGenerator + ">" + areaGen); logger.info(" - plot world: {}", pa);
PlotSquared.log(Captions.PREFIX + "&3 - plotworld: &7" + pa); logger.info(" - plot area manager: {}", pa.getPlotManager());
PlotSquared.log(Captions.PREFIX + "&3 - plotAreaManager: &7" + pa.getPlotManager());
areaGen.getPlotGenerator().initialize(pa); areaGen.getPlotGenerator().initialize(pa);
areaGen.augment(pa); areaGen.augment(pa);
addPlotArea(pa); addPlotArea(pa);
@ -1264,7 +1233,7 @@ public class PlotSquared {
+ PlotAreaType.AUGMENTED + "`"); + PlotAreaType.AUGMENTED + "`");
} }
for (String areaId : areasSection.getKeys(false)) { for (String areaId : areasSection.getKeys(false)) {
PlotSquared.log(Captions.PREFIX + " - " + areaId); logger.info(" - {}", areaId);
String[] split = areaId.split("(?<=[^;-])-"); String[] split = areaId.split("(?<=[^;-])-");
if (split.length != 3) { if (split.length != 3) {
throw new IllegalArgumentException("Invalid Area identifier: " + areaId throw new IllegalArgumentException("Invalid Area identifier: " + areaId
@ -1326,11 +1295,10 @@ public class PlotSquared {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
PlotSquared.log(Captions.PREFIX + "&aDetected area load for '" + world + "'"); logger.info("Detected area load for '{}'", world);
PlotSquared logger.info(" | generator: {}>{}", baseGenerator, areaGen);
.log(Captions.PREFIX + "&c | &9generator: &7" + baseGenerator + ">" + areaGen); logger.info(" | plot world: {}", pa);
PlotSquared.log(Captions.PREFIX + "&c | &9plotworld: &7" + pa); logger.info(" | manager: {}", pa.getPlotManager());
PlotSquared.log(Captions.PREFIX + "&c | &9manager: &7" + pa.getPlotManager());
areaGen.getPlotGenerator().initialize(pa); areaGen.getPlotGenerator().initialize(pa);
areaGen.augment(pa); areaGen.augment(pa);
addPlotArea(pa); addPlotArea(pa);
@ -1399,7 +1367,7 @@ public class PlotSquared {
for (String element : split) { for (String element : split) {
String[] pair = element.split("="); String[] pair = element.split("=");
if (pair.length != 2) { if (pair.length != 2) {
PlotSquared.log("&cNo value provided for: &7" + element); logger.error("No value provided for '{}'", element);
return false; return false;
} }
String key = pair[0].toLowerCase(); String key = pair[0].toLowerCase();
@ -1447,12 +1415,12 @@ public class PlotSquared {
ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString()); ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString());
break; break;
default: default:
PlotSquared.log("&cKey not found: &7" + element); logger.error("Key not found: {}", element);
return false; return false;
} }
} catch (Exception e) { } catch (Exception e) {
logger.error("Invalid value '{}' for arg '{}'", value, element);
e.printStackTrace(); e.printStackTrace();
PlotSquared.log("&cInvalid value: &7" + value + " in arg " + element);
return false; return false;
} }
} }
@ -1530,8 +1498,8 @@ public class PlotSquared {
} }
} }
} catch (IOException e) { } catch (IOException e) {
logger.error("Could not save {}", file);
e.printStackTrace(); e.printStackTrace();
PlotSquared.log("&cCould not save " + file);
} }
} }
@ -1566,8 +1534,8 @@ public class PlotSquared {
// Close the connection // Close the connection
DBFunc.close(); DBFunc.close();
} catch (NullPointerException throwable) { } catch (NullPointerException throwable) {
logger.error("Could not close database connection", throwable);
throwable.printStackTrace(); throwable.printStackTrace();
PlotSquared.log("&cCould not close database connection!");
} }
} }
@ -1579,10 +1547,9 @@ public class PlotSquared {
HybridUtils.regions.isEmpty() && HybridUtils.chunks.isEmpty())) { HybridUtils.regions.isEmpty() && HybridUtils.chunks.isEmpty())) {
return; return;
} }
PlotSquared.log( logger.info("Road regeneration incomplete. Saving incomplete regions to disk");
Captions.PREFIX + "Road regeneration incomplete. Saving incomplete regions to disk."); logger.info(" - regions: {}", HybridUtils.regions.size());
PlotSquared.debug(" Regions: " + HybridUtils.regions.size()); logger.info(" - chunks: {}", HybridUtils.chunks.size());
PlotSquared.debug(" Chunks: " + HybridUtils.chunks.size());
ArrayList<int[]> regions = new ArrayList<>(); ArrayList<int[]> regions = new ArrayList<>();
ArrayList<int[]> chunks = new ArrayList<>(); ArrayList<int[]> chunks = new ArrayList<>();
for (BlockVector2 r : HybridUtils.regions) { for (BlockVector2 r : HybridUtils.regions) {
@ -1599,16 +1566,14 @@ public class PlotSquared {
this.IMP.getDirectory() + File.separator + "persistent_regen_data_" + HybridUtils.area this.IMP.getDirectory() + File.separator + "persistent_regen_data_" + HybridUtils.area
.getId() + "_" + HybridUtils.area.getWorldName()); .getId() + "_" + HybridUtils.area.getWorldName());
if (file.exists() && !file.delete()) { if (file.exists() && !file.delete()) {
PlotSquared.log(Captions.PREFIX logger.error("persistent_regene_data file already exists and could not be deleted");
+ "persistent_regen_data file already exists and could not be deleted.");
return; return;
} }
try (ObjectOutputStream oos = new ObjectOutputStream( try (ObjectOutputStream oos = new ObjectOutputStream(
Files.newOutputStream(file.toPath(), StandardOpenOption.CREATE_NEW))) { Files.newOutputStream(file.toPath(), StandardOpenOption.CREATE_NEW))) {
oos.writeObject(list); oos.writeObject(list);
} catch (IOException e) { } catch (IOException e) {
PlotSquared.log(Captions.PREFIX + "Error create persistent_regen_data file."); logger.error("Error creating persistent_region_data file", e);
e.printStackTrace();
} }
} }
@ -1628,7 +1593,7 @@ public class PlotSquared {
File file = MainUtil.getFile(IMP.getDirectory(), Storage.SQLite.DB + ".db"); File file = MainUtil.getFile(IMP.getDirectory(), Storage.SQLite.DB + ".db");
database = new SQLite(file); database = new SQLite(file);
} else { } else {
PlotSquared.log(Captions.PREFIX + "&cNo storage type is set!"); logger.error("No storage type is set. Disabling PlotSquared");
this.IMP.shutdown(); //shutdown used instead of disable because no database is set this.IMP.shutdown(); //shutdown used instead of disable because no database is set
return; return;
} }
@ -1646,19 +1611,12 @@ public class PlotSquared {
} }
this.clusters_tmp = DBFunc.getClusters(); this.clusters_tmp = DBFunc.getClusters();
} catch (ClassNotFoundException | SQLException e) { } catch (ClassNotFoundException | SQLException e) {
PlotSquared.log(Captions.PREFIX logger.error("Failed to open database connection ({}). Disabling PlotSquared", Storage.MySQL.USE ? "MySQL" : "SQLite");
+ "&cFailed to open DATABASE connection. The plugin will disable itself."); logger.error("==== Here is an ugly stacktrace, if you are interested in those things ===");
if (Storage.MySQL.USE) {
PlotSquared.log("$4MYSQL");
} else if (Storage.SQLite.USE) {
PlotSquared.log("$4SQLITE");
}
PlotSquared.log(
"&d==== Here is an ugly stacktrace, if you are interested in those things ===");
e.printStackTrace(); e.printStackTrace();
PlotSquared.log("&d==== End of stacktrace ===="); logger.error("&d==== End of stacktrace ====");
PlotSquared.log("&6Please go to the " + IMP.getPluginName() logger.error("&6Please go to the {} 'storage.yml' and configure the database correctly",
+ " 'storage.yml' and configure the database correctly."); imp().getPluginName());
this.IMP.shutdown(); //shutdown used instead of disable because of database error this.IMP.shutdown(); //shutdown used instead of disable because of database error
} }
} }
@ -1683,7 +1641,7 @@ public class PlotSquared {
try { try {
worlds.save(worldsFile); worlds.save(worldsFile);
} catch (IOException e) { } catch (IOException e) {
PlotSquared.debug("Failed to save " + IMP.getPluginName() + " worlds.yml"); logger.error("Failed to save worlds.yml", e);
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -1716,14 +1674,12 @@ public class PlotSquared {
public boolean setupConfigs() { public boolean setupConfigs() {
File folder = new File(this.IMP.getDirectory(), "config"); File folder = new File(this.IMP.getDirectory(), "config");
if (!folder.exists() && !folder.mkdirs()) { if (!folder.exists() && !folder.mkdirs()) {
PlotSquared.log(Captions.PREFIX logger.error("Failed to create the /plugins/config folder. Please create it manually");
+ "&cFailed to create the /plugins/config folder. Please create it manually.");
} }
try { try {
this.worldsFile = new File(folder, "worlds.yml"); this.worldsFile = new File(folder, "worlds.yml");
if (!this.worldsFile.exists() && !this.worldsFile.createNewFile()) { if (!this.worldsFile.exists() && !this.worldsFile.createNewFile()) {
PlotSquared.log( logger.error("Could not create the worlds file. Please create 'worlds.yml' manually");
"Could not create the worlds file, please create \"worlds.yml\" manually.");
} }
this.worlds = YamlConfiguration.loadConfiguration(this.worldsFile); this.worlds = YamlConfiguration.loadConfiguration(this.worldsFile);
@ -1733,21 +1689,20 @@ public class PlotSquared {
.equalsIgnoreCase(LegacyConverter.CONFIGURATION_VERSION) && !this.worlds .equalsIgnoreCase(LegacyConverter.CONFIGURATION_VERSION) && !this.worlds
.getString("configuration_version").equalsIgnoreCase("v5"))) { .getString("configuration_version").equalsIgnoreCase("v5"))) {
// Conversion needed // Conversion needed
log(Captions.LEGACY_CONFIG_FOUND.getTranslated()); logger.info(Captions.LEGACY_CONFIG_FOUND.getTranslated());
try { try {
com.google.common.io.Files com.google.common.io.Files
.copy(this.worldsFile, new File(folder, "worlds.yml.old")); .copy(this.worldsFile, new File(folder, "worlds.yml.old"));
log(Captions.LEGACY_CONFIG_BACKUP.getTranslated()); logger.info(Captions.LEGACY_CONFIG_BACKUP.getTranslated());
final ConfigurationSection worlds = final ConfigurationSection worlds =
this.worlds.getConfigurationSection("worlds"); this.worlds.getConfigurationSection("worlds");
final LegacyConverter converter = new LegacyConverter(worlds); final LegacyConverter converter = new LegacyConverter(worlds);
converter.convert(); converter.convert();
this.worlds.set("worlds", worlds); this.worlds.set("worlds", worlds);
this.setConfigurationVersion(LegacyConverter.CONFIGURATION_VERSION); this.setConfigurationVersion(LegacyConverter.CONFIGURATION_VERSION);
log(Captions.LEGACY_CONFIG_DONE.getTranslated()); logger.info(Captions.LEGACY_CONFIG_DONE.getTranslated());
} catch (final Exception e) { } catch (final Exception e) {
log(Captions.LEGACY_CONFIG_CONVERSION_FAILED.getTranslated()); logger.error(Captions.LEGACY_CONFIG_CONVERSION_FAILED.getTranslated(), e);
e.printStackTrace();
} }
// Disable plugin // Disable plugin
this.IMP.shutdown(); this.IMP.shutdown();
@ -1757,18 +1712,17 @@ public class PlotSquared {
this.worlds.set("configuration_version", LegacyConverter.CONFIGURATION_VERSION); this.worlds.set("configuration_version", LegacyConverter.CONFIGURATION_VERSION);
} }
} catch (IOException ignored) { } catch (IOException ignored) {
PlotSquared.log("Failed to save settings.yml"); logger.error("Failed to save worlds.yml");
} }
try { try {
this.configFile = new File(folder, "settings.yml"); this.configFile = new File(folder, "settings.yml");
if (!this.configFile.exists() && !this.configFile.createNewFile()) { if (!this.configFile.exists() && !this.configFile.createNewFile()) {
PlotSquared.log( logger.error("Could not create the settings file. Please create 'settings.yml' manually");
"Could not create the settings file, please create \"settings.yml\" manually.");
} }
this.config = YamlConfiguration.loadConfiguration(this.configFile); this.config = YamlConfiguration.loadConfiguration(this.configFile);
setupConfig(); setupConfig();
} catch (IOException ignored) { } catch (IOException ignored) {
PlotSquared.log("Failed to save settings.yml"); logger.error("Failed to save settings.yml");
} }
try { try {
this.styleFile = MainUtil.getFile(IMP.getDirectory(), this.styleFile = MainUtil.getFile(IMP.getDirectory(),
@ -1778,43 +1732,38 @@ public class PlotSquared {
this.styleFile.getParentFile().mkdirs(); this.styleFile.getParentFile().mkdirs();
} }
if (!this.styleFile.createNewFile()) { if (!this.styleFile.createNewFile()) {
PlotSquared.log( logger.error("Failed to create the style file. Please create 'translations/style.yml' manually");
"Could not create the style file, please create \"translations/style.yml\" manually");
} }
} }
this.style = YamlConfiguration.loadConfiguration(this.styleFile); this.style = YamlConfiguration.loadConfiguration(this.styleFile);
setupStyle(); setupStyle();
} catch (IOException err) { } catch (IOException ignored) {
err.printStackTrace(); logger.error("Failed to save style.yml");
PlotSquared.log("Failed to save style.yml");
} }
try { try {
this.storageFile = new File(folder, "storage.yml"); this.storageFile = new File(folder, "storage.yml");
if (!this.storageFile.exists() && !this.storageFile.createNewFile()) { if (!this.storageFile.exists() && !this.storageFile.createNewFile()) {
PlotSquared.log( logger.error("Could not create the storage settings file. Please create 'storage.yml' manually");
"Could not the storage settings file, please create \"storage.yml\" manually.");
} }
this.storage = YamlConfiguration.loadConfiguration(this.storageFile); this.storage = YamlConfiguration.loadConfiguration(this.storageFile);
setupStorage(); setupStorage();
} catch (IOException ignored) { } catch (IOException ignored) {
PlotSquared.log("Failed to save storage.yml"); logger.error("Failed to save storage.yml");
} }
try { try {
this.commandsFile = new File(folder, "commands.yml"); this.commandsFile = new File(folder, "commands.yml");
if (!this.commandsFile.exists() && !this.commandsFile.createNewFile()) { if (!this.commandsFile.exists() && !this.commandsFile.createNewFile()) {
PlotSquared.log( logger.error("Could not create the commands file. Please create 'commands.yml' manually");
"Could not the storage settings file, please create \"commands.yml\" manually.");
} }
this.commands = YamlConfiguration.loadConfiguration(this.commandsFile); this.commands = YamlConfiguration.loadConfiguration(this.commandsFile);
} catch (IOException ignored) { } catch (IOException ignored) {
PlotSquared.log("Failed to save commands.yml"); logger.error("Failed to save commands.yml");
} }
try { try {
this.style.save(this.styleFile); this.style.save(this.styleFile);
this.commands.save(this.commandsFile); this.commands.save(this.commandsFile);
} catch (IOException e) { } catch (IOException e) {
PlotSquared.log("Configuration file saving failed"); logger.error("Configuration file saving failed", e);
e.printStackTrace();
} }
return true; return true;
} }
@ -1845,9 +1794,7 @@ public class PlotSquared {
if (Settings.DEBUG) { if (Settings.DEBUG) {
Map<String, Object> components = Settings.getFields(Settings.Enabled_Components.class); Map<String, Object> components = Settings.getFields(Settings.Enabled_Components.class);
for (Entry<String, Object> component : components.entrySet()) { for (Entry<String, Object> component : components.entrySet()) {
PlotSquared.log(Captions.PREFIX + String logger.debug("Key: {} | Value: {}", component.getKey(), component.getValue());
.format("&cKey: &6%s&c, Value: &6%s", component.getKey(),
component.getValue()));
} }
} }
} }

View File

@ -36,6 +36,8 @@ import com.plotsquared.core.util.entity.EntityCategory;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import com.plotsquared.core.uuid.UUIDMapping; import com.plotsquared.core.uuid.UUIDMapping;
import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.entity.EntityType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection; import java.util.Collection;
import java.util.Comparator; import java.util.Comparator;
@ -48,6 +50,8 @@ import java.util.Map;
permission = "plots.admin") permission = "plots.admin")
public class Debug extends SubCommand { public class Debug extends SubCommand {
private static final Logger logger = LoggerFactory.getLogger(Debug.class);
@Override public boolean onCommand(PlotPlayer<?> player, String[] args) { @Override public boolean onCommand(PlotPlayer<?> player, String[] args) {
if (args.length > 0) { if (args.length > 0) {
if ("player".equalsIgnoreCase(args[0])) { if ("player".equalsIgnoreCase(args[0])) {
@ -79,6 +83,13 @@ public class Debug extends SubCommand {
} }
return true; return true;
} }
if (args.length > 0 && "logging".equalsIgnoreCase(args[0])) {
logger.info("Info!");
logger.warn("Warning!");
logger.error("Error!", new RuntimeException());
logger.debug("Debug!");
return true;
}
if (args.length > 0 && "entitytypes".equalsIgnoreCase(args[0])) { if (args.length > 0 && "entitytypes".equalsIgnoreCase(args[0])) {
EntityCategories.init(); EntityCategories.init();
player.sendMessage(Captions.PREFIX.getTranslated() + "§cEntity Categories: "); player.sendMessage(Captions.PREFIX.getTranslated() + "§cEntity Categories: ");

View File

@ -59,6 +59,8 @@ import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3; import com.plotsquared.core.util.task.RunnableVal3;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.Bindings; import javax.script.Bindings;
import javax.script.ScriptContext; import javax.script.ScriptContext;
@ -81,6 +83,9 @@ import java.util.concurrent.CompletableFuture;
aliases = {"exec", "$"}, aliases = {"exec", "$"},
category = CommandCategory.DEBUG) category = CommandCategory.DEBUG)
public class DebugExec extends SubCommand { public class DebugExec extends SubCommand {
private static final Logger logger = LoggerFactory.getLogger(DebugExec.class);
private ScriptEngine engine; private ScriptEngine engine;
private Bindings scope; private Bindings scope;
@ -459,14 +464,12 @@ public class DebugExec extends SubCommand {
} catch (ScriptException e) { } catch (ScriptException e) {
e.printStackTrace(); e.printStackTrace();
} }
PlotSquared logger.info("> {}ms -> {}", System.currentTimeMillis() - start, result);
.log("> " + (System.currentTimeMillis() - start) + "ms -> " + result);
}); });
} else { } else {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
Object result = this.engine.eval(script, this.scope); Object result = this.engine.eval(script, this.scope);
PlotSquared logger.info("> {}ms -> {}", System.currentTimeMillis() - start, result);
.log("> " + (System.currentTimeMillis() - start) + "ms -> " + result);
} }
return true; return true;
} catch (ScriptException e) { } catch (ScriptException e) {

View File

@ -36,6 +36,8 @@ import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.util.StringMan; import com.plotsquared.core.util.StringMan;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@ -53,6 +55,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
confirmation = true) confirmation = true)
public class Purge extends SubCommand { public class Purge extends SubCommand {
private static final Logger logger = LoggerFactory.getLogger(Purge.class);
@Override public boolean onCommand(final PlotPlayer<?> player, String[] args) { @Override public boolean onCommand(final PlotPlayer<?> player, String[] args) {
if (args.length == 0) { if (args.length == 0) {
Captions.COMMAND_SYNTAX.send(player, getUsage()); Captions.COMMAND_SYNTAX.send(player, getUsage());
@ -170,6 +174,7 @@ public class Purge extends SubCommand {
"/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)"; "/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)";
boolean finalClear = clear; boolean finalClear = clear;
Runnable run = () -> { Runnable run = () -> {
logger.debug("Calculating plots to purge, please wait...");
PlotSquared.debug("Calculating plots to purge, please wait..."); PlotSquared.debug("Calculating plots to purge, please wait...");
HashSet<Integer> ids = new HashSet<>(); HashSet<Integer> ids = new HashSet<>();
Iterator<Plot> iterator = toDelete.iterator(); Iterator<Plot> iterator = toDelete.iterator();
@ -183,22 +188,18 @@ public class Purge extends SubCommand {
try { try {
ids.add(plot.temp); ids.add(plot.temp);
if (finalClear) { if (finalClear) {
plot.clear(false, true, () -> PlotSquared plot.clear(false, true, () ->
.debug("Plot " + plot.getId() + " cleared by purge.")); logger.debug("Plot {} cleared by purge", plot.getId()));
} else { } else {
plot.removeSign(); plot.removeSign();
} }
plot.getArea().removePlot(plot.getId()); plot.getArea().removePlot(plot.getId());
for (PlotPlayer pp : plot.getPlayersInPlot()) { for (PlotPlayer<?> pp : plot.getPlayersInPlot()) {
PlotListener.plotEntry(pp, plot); PlotListener.plotEntry(pp, plot);
} }
} catch (NullPointerException e) { } catch (NullPointerException e) {
PlotSquared.log( logger.error("NullPointer during purge detected. This is likely"
"NullPointer during purge detected. This is likely because you are " + " because you are deleting a world that has been removed", e);
+ "deleting a world that has been removed.");
if (Settings.DEBUG) {
e.printStackTrace();
}
} }
} }
cleared.set(true); cleared.set(true);

View File

@ -42,6 +42,8 @@ import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -62,6 +64,7 @@ import java.util.Set;
category = CommandCategory.ADMINISTRATION) category = CommandCategory.ADMINISTRATION)
public class Trim extends SubCommand { public class Trim extends SubCommand {
private static final Logger logger = LoggerFactory.getLogger(Trim.class);
public static ArrayList<Plot> expired = null; public static ArrayList<Plot> expired = null;
private static volatile boolean TASK = false; private static volatile boolean TASK = false;
@ -179,14 +182,15 @@ public class Trim extends SubCommand {
@Override public void run(Set<BlockVector2> viable, final Set<BlockVector2> nonViable) { @Override public void run(Set<BlockVector2> viable, final Set<BlockVector2> nonViable) {
Runnable regenTask; Runnable regenTask;
if (regen) { if (regen) {
PlotSquared.log("Starting regen task:"); logger.info("Starting regen task");
PlotSquared.log(" - This is a VERY slow command"); logger.info(" - This is a VERY slow command");
PlotSquared.log(" - It will say `Trim done!` when complete"); logger.info(" - It will say 'Trim done!' when complete");
regenTask = new Runnable() { regenTask = new Runnable() {
@Override public void run() { @Override public void run() {
if (nonViable.isEmpty()) { if (nonViable.isEmpty()) {
Trim.TASK = false; Trim.TASK = false;
player.sendMessage("Trim done!"); player.sendMessage("Trim done!");
logger.info("Trim done!");
return; return;
} }
Iterator<BlockVector2> iterator = nonViable.iterator(); Iterator<BlockVector2> iterator = nonViable.iterator();

View File

@ -44,6 +44,8 @@ import com.plotsquared.core.util.Permissions;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.world.item.ItemTypes; import com.sk89q.worldedit.world.item.ItemTypes;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -57,6 +59,8 @@ import java.util.stream.Collectors;
public class ComponentPresetManager { public class ComponentPresetManager {
private static final Logger logger = LoggerFactory.getLogger(ComponentPresetManager.class);
private final List<ComponentPreset> presets; private final List<ComponentPreset> presets;
private final String guiName; private final String guiName;
@ -70,7 +74,7 @@ public class ComponentPresetManager {
e.printStackTrace(); e.printStackTrace();
} }
if (!created) { if (!created) {
PlotSquared.log(Captions.PREFIX + "Failed to create components.yml"); logger.error("Failed to create components.yml");
this.guiName = "&cInvalid!"; this.guiName = "&cInvalid!";
this.presets = new ArrayList<>(); this.presets = new ArrayList<>();
return; return;
@ -86,8 +90,7 @@ public class ComponentPresetManager {
try { try {
yamlConfiguration.save(file); yamlConfiguration.save(file);
} catch (IOException e) { } catch (IOException e) {
PlotSquared.log(Captions.PREFIX + "Failed to save default values to components.yml"); logger.error("Failed to save default values to components.yml", e);
e.printStackTrace();
} }
} }
this.guiName = yamlConfiguration.getString("title", "&6Plot Components"); this.guiName = yamlConfiguration.getString("title", "&6Plot Components");
@ -105,8 +108,7 @@ public class ComponentPresetManager {
try { try {
yamlConfiguration.save(file); yamlConfiguration.save(file);
} catch (final IOException e) { } catch (final IOException e) {
PlotSquared.log(Captions.PREFIX + "Failed to save default values to components.yml"); logger.error("Failed to save default values to components.yml", e);
e.printStackTrace();
} }
this.presets = defaultPreset; this.presets = defaultPreset;
} }

View File

@ -27,7 +27,6 @@ package com.plotsquared.core.database;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.plotsquared.core.PlotSquared; import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.ConfigurationSection; import com.plotsquared.core.configuration.ConfigurationSection;
import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.configuration.Storage; import com.plotsquared.core.configuration.Storage;
@ -48,6 +47,8 @@ import com.plotsquared.core.util.StringMan;
import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DatabaseMetaData; import java.sql.DatabaseMetaData;
@ -79,6 +80,8 @@ import java.util.concurrent.atomic.AtomicInteger;
@SuppressWarnings("SqlDialectInspection") @SuppressWarnings("SqlDialectInspection")
public class SQLManager implements AbstractDB { public class SQLManager implements AbstractDB {
private static final Logger logger = LoggerFactory.getLogger(SQLManager.class);
// Public final // Public final
public final String SET_OWNER; public final String SET_OWNER;
public final String GET_ALL_PLOTS; public final String GET_ALL_PLOTS;
@ -355,11 +358,12 @@ public class SQLManager implements AbstractDB {
try { try {
task.run(); task.run();
} catch (Throwable e) { } catch (Throwable e) {
PlotSquared.debug("============ DATABASE ERROR ============"); logger.debug("============ DATABASE ERROR ============");
PlotSquared.debug("There was an error updating the database."); logger.debug("============ DATABASE ERROR ============");
PlotSquared.debug(" - It will be corrected on shutdown"); logger.debug("There was an error updating the database.");
logger.debug(" - It will be corrected on shutdown");
e.printStackTrace(); e.printStackTrace();
PlotSquared.debug("========================================"); logger.debug("========================================");
} }
} }
commit(); commit();
@ -409,12 +413,12 @@ public class SQLManager implements AbstractDB {
} }
lastTask = task; lastTask = task;
} catch (Throwable e) { } catch (Throwable e) {
PlotSquared.debug("============ DATABASE ERROR ============"); logger.debug("============ DATABASE ERROR ============");
PlotSquared.debug("There was an error updating the database."); logger.debug("There was an error updating the database.");
PlotSquared.debug(" - It will be corrected on shutdown"); logger.debug(" - It will be corrected on shutdown");
PlotSquared.debug("========================================"); logger.debug("========================================");
e.printStackTrace(); e.printStackTrace();
PlotSquared.debug("========================================"); logger.debug("========================================");
} }
} }
if (statement != null && task != null) { if (statement != null && task != null) {
@ -454,12 +458,12 @@ public class SQLManager implements AbstractDB {
} }
lastTask = task; lastTask = task;
} catch (Throwable e) { } catch (Throwable e) {
PlotSquared.debug("============ DATABASE ERROR ============"); logger.debug("============ DATABASE ERROR ============");
PlotSquared.debug("There was an error updating the database."); logger.debug("There was an error updating the database.");
PlotSquared.debug(" - It will be corrected on shutdown"); logger.debug(" - It will be corrected on shutdown");
PlotSquared.debug("========================================"); logger.debug("========================================");
e.printStackTrace(); e.printStackTrace();
PlotSquared.debug("========================================"); logger.debug("========================================");
} }
} }
if (statement != null && task != null) { if (statement != null && task != null) {
@ -500,12 +504,12 @@ public class SQLManager implements AbstractDB {
} }
lastTask = task; lastTask = task;
} catch (Throwable e) { } catch (Throwable e) {
PlotSquared.debug("============ DATABASE ERROR ============"); logger.debug("============ DATABASE ERROR ============");
PlotSquared.debug("There was an error updating the database."); logger.debug("There was an error updating the database.");
PlotSquared.debug(" - It will be corrected on shutdown"); logger.debug(" - It will be corrected on shutdown");
PlotSquared.debug("========================================"); logger.debug("========================================");
e.printStackTrace(); e.printStackTrace();
PlotSquared.debug("========================================"); logger.debug("========================================");
} }
} }
if (statement != null && task != null) { if (statement != null && task != null) {
@ -529,12 +533,12 @@ public class SQLManager implements AbstractDB {
this.plotTasks.clear(); this.plotTasks.clear();
} }
} catch (Throwable e) { } catch (Throwable e) {
PlotSquared.debug("============ DATABASE ERROR ============"); logger.debug("============ DATABASE ERROR ============");
PlotSquared.debug("There was an error updating the database."); logger.debug("There was an error updating the database.");
PlotSquared.debug(" - It will be corrected on shutdown"); logger.debug(" - It will be corrected on shutdown");
PlotSquared.debug("========================================"); logger.debug("========================================");
e.printStackTrace(); e.printStackTrace();
PlotSquared.debug("========================================"); logger.debug("========================================");
} }
return false; return false;
} }
@ -633,8 +637,7 @@ public class SQLManager implements AbstractDB {
} }
}); });
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.debug("Warning! Failed to set all helper for plots", e);
PlotSquared.debug("&7[WARN] Failed to set all helpers for plots");
try { try {
SQLManager.this.connection.commit(); SQLManager.this.connection.commit();
} catch (SQLException e1) { } catch (SQLException e1) {
@ -703,21 +706,15 @@ public class SQLManager implements AbstractDB {
try { try {
preparedStatement.executeBatch(); preparedStatement.executeBatch();
} catch (final Exception e) { } catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated() logger.error("Failed to store flag values for plot with entry ID: {}", e);
+ "Failed to store flag values for plot with entry ID: " + plot.getId());
e.printStackTrace();
continue; continue;
} }
PlotSquared.debug(Captions.PREFIX.getTranslated() logger.debug("- Finished converting flag values for plot with entry ID: {}", plot.getId());
+ "- Finished converting flags for plot with entry ID: " + plot.getId());
} }
} catch (final Exception e) { } catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "Failed to store flag values:"); logger.error("Failed to store flag values", e);
e.printStackTrace();
} }
PlotSquared.log( logger.info("Finished converting flags ({} plots processed)", plots.size());
Captions.PREFIX.getTranslated() + "Finished converting flags (" + plots.size()
+ " plots processed)");
whenDone.run(); whenDone.run();
} }
@ -825,8 +822,7 @@ public class SQLManager implements AbstractDB {
last = subList.size(); last = subList.size();
preparedStmt.addBatch(); preparedStmt.addBatch();
} }
PlotSquared.debug( logger.debug("Batch 1: {} | {}", count, objList.get(0).getClass().getCanonicalName());
"&aBatch 1: " + count + " | " + objList.get(0).getClass().getCanonicalName());
preparedStmt.executeBatch(); preparedStmt.executeBatch();
preparedStmt.clearParameters(); preparedStmt.clearParameters();
preparedStmt.close(); preparedStmt.close();
@ -836,8 +832,8 @@ public class SQLManager implements AbstractDB {
return; return;
} catch (SQLException e) { } catch (SQLException e) {
if (this.mySQL) { if (this.mySQL) {
logger.error("1: | {}", objList.get(0).getClass().getCanonicalName());
e.printStackTrace(); e.printStackTrace();
PlotSquared.debug("&cERROR 1: | " + objList.get(0).getClass().getCanonicalName());
} }
} }
try { try {
@ -869,26 +865,25 @@ public class SQLManager implements AbstractDB {
last = subList.size(); last = subList.size();
preparedStmt.addBatch(); preparedStmt.addBatch();
} }
PlotSquared.debug( logger.debug("Batch 2: {} | {}", count, objList.get(0).getClass().getCanonicalName());
"&aBatch 2: " + count + " | " + objList.get(0).getClass().getCanonicalName());
preparedStmt.executeBatch(); preparedStmt.executeBatch();
preparedStmt.clearParameters(); preparedStmt.clearParameters();
preparedStmt.close(); preparedStmt.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
PlotSquared.debug("&cERROR 2: | " + objList.get(0).getClass().getCanonicalName()); logger.error("2: | {}", objList.get(0).getClass().getCanonicalName());
PlotSquared.debug("&6[WARN] Could not bulk save!"); logger.error("Could not bulk save!");
try (PreparedStatement preparedStmt = this.connection try (PreparedStatement preparedStmt = this.connection
.prepareStatement(mod.getCreateSQL())) { .prepareStatement(mod.getCreateSQL())) {
for (T obj : objList) { for (T obj : objList) {
mod.setSQL(preparedStmt, obj); mod.setSQL(preparedStmt, obj);
preparedStmt.addBatch(); preparedStmt.addBatch();
} }
PlotSquared.debug("&aBatch 3"); logger.debug("Batch 3");
preparedStmt.executeBatch(); preparedStmt.executeBatch();
} catch (SQLException e3) { } catch (SQLException e3) {
logger.error("Failed to save all", e);
e3.printStackTrace(); e3.printStackTrace();
PlotSquared.debug("&c[ERROR] Failed to save all!");
} }
} }
if (whenDone != null) { if (whenDone != null) {
@ -939,9 +934,7 @@ public class SQLManager implements AbstractDB {
try { try {
preparedStatement.executeBatch(); preparedStatement.executeBatch();
} catch (final Exception e) { } catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated() logger.error("Failed to store settings for plot with entry ID: {}", legacySettings.id);
+ "Failed to store settings values for plot with entry ID: "
+ legacySettings.id);
e.printStackTrace(); e.printStackTrace();
continue; continue;
} }
@ -953,18 +946,13 @@ public class SQLManager implements AbstractDB {
try { try {
preparedStatement.executeBatch(); preparedStatement.executeBatch();
} catch (final Exception e) { } catch (final Exception e) {
PlotSquared logger.error("Failed to store settings", e);
.log(Captions.PREFIX.getTranslated() + "Failed to store settings values");
e.printStackTrace();
} }
} }
} catch (final Exception e) { } catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "Failed to store settings values:"); logger.error("Failed to store settings", e);
e.printStackTrace();
} }
PlotSquared.log( logger.info("Finished converting settihgs ({} plots processed)", myList.size());
Captions.PREFIX.getTranslated() + "Finished converting settings (" + myList.size()
+ " plots processed)");
whenDone.run(); whenDone.run();
} }
@ -1143,7 +1131,7 @@ public class SQLManager implements AbstractDB {
return; return;
} }
boolean addConstraint = create == tables.length; boolean addConstraint = create == tables.length;
PlotSquared.debug("Creating tables"); logger.debug("Creating tables");
try (Statement stmt = this.connection.createStatement()) { try (Statement stmt = this.connection.createStatement()) {
if (this.mySQL) { if (this.mySQL) {
stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + this.prefix + "plot` (" stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + this.prefix + "plot` ("
@ -1383,9 +1371,8 @@ public class SQLManager implements AbstractDB {
* @param plot * @param plot
*/ */
@Override public void delete(final Plot plot) { @Override public void delete(final Plot plot) {
PlotSquared.debug( logger.debug("Deleting plot. ID: {} | World: {} | Owner: {} | Index: {}",
"Deleting plot... Id: " + plot.getId() + " World: " + plot.getWorldName() + " Owner: " plot.getId(), plot.getWorldName(), plot.getOwnerAbs(), plot.temp);
+ plot.getOwnerAbs() + " Index: " + plot.temp);
deleteSettings(plot); deleteSettings(plot);
deleteDenied(plot); deleteDenied(plot);
deleteHelpers(plot); deleteHelpers(plot);
@ -1411,9 +1398,8 @@ public class SQLManager implements AbstractDB {
* @param plot * @param plot
*/ */
@Override public void createPlotSettings(final int id, Plot plot) { @Override public void createPlotSettings(final int id, Plot plot) {
PlotSquared.debug( logger.debug("Creating plot plot. ID: {} | World: {} | Owner: {} | Index: {}",
"Creating plot... Id: " + plot.getId() + " World: " + plot.getWorldName() + " Owner: " plot.getId(), plot.getWorldName(), plot.getOwnerAbs(), plot.temp);
+ plot.getOwnerAbs() + " Index: " + id);
addPlotTask(plot, new UniqueStatement("createPlotSettings") { addPlotTask(plot, new UniqueStatement("createPlotSettings") {
@Override public void set(PreparedStatement statement) throws SQLException { @Override public void set(PreparedStatement statement) throws SQLException {
statement.setInt(1, id); statement.setInt(1, id);
@ -1571,7 +1557,7 @@ public class SQLManager implements AbstractDB {
"SELECT plot_plot_id, user_uuid, COUNT(*) FROM " + this.prefix + table "SELECT plot_plot_id, user_uuid, COUNT(*) FROM " + this.prefix + table
+ " GROUP BY plot_plot_id, user_uuid HAVING COUNT(*) > 1"); + " GROUP BY plot_plot_id, user_uuid HAVING COUNT(*) > 1");
if (result.next()) { if (result.next()) {
PlotSquared.debug("BACKING UP: " + this.prefix + table); logger.debug("Backing up {}", this.prefix + table);
result.close(); result.close();
statement.executeUpdate( statement.executeUpdate(
"CREATE TABLE " + this.prefix + table + "_tmp AS SELECT * FROM " "CREATE TABLE " + this.prefix + table + "_tmp AS SELECT * FROM "
@ -1581,7 +1567,7 @@ public class SQLManager implements AbstractDB {
"CREATE TABLE " + this.prefix + table + " AS SELECT * FROM " "CREATE TABLE " + this.prefix + table + " AS SELECT * FROM "
+ this.prefix + table + "_tmp"); + this.prefix + table + "_tmp");
statement.executeUpdate("DROP TABLE " + this.prefix + table + "_tmp"); statement.executeUpdate("DROP TABLE " + this.prefix + table + "_tmp");
PlotSquared.debug("RESTORING: " + this.prefix + table); logger.debug("Restoring {}", this.prefix + table);
} }
} }
} catch (SQLException e2) { } catch (SQLException e2) {
@ -1645,40 +1631,20 @@ public class SQLManager implements AbstractDB {
try { try {
String flag_str = String flag_str =
split[1].replaceAll("¯", ":").replaceAll("\u00B4", ","); split[1].replaceAll("¯", ":").replaceAll("\u00B4", ",");
/*PlotFlag<?, ?> flag = GlobalFlagContainer.getInstance().getFlagFromString(split[0]);
if (flag == null) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "Flag not found and therefore ignored: " + split[0]);
continue;
}*/
flagMap.get(id).put(split[0], flag_str); flagMap.get(id).put(split[0], flag_str);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} /*else {
element = element.replaceAll("\u00AF", ":").replaceAll("\u00B4", ",");
if (StringMan
.isAlpha(element.replaceAll("_", "").replaceAll("-", ""))) {
PlotFlag<?, ?> flag = GlobalFlagContainer.getInstance().getFlagFromString(element);
if (flag == null) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "Flag not found and therefore ignored: " + element);
} }
} else {
PlotSquared.log(Captions.PREFIX.getTranslated() + "INVALID FLAG: " + element);
}
}*/
} }
} }
} }
} catch (final Exception e) { } catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "Failed to load old flag values:"); logger.error("Failed to load old flag values", e);
e.printStackTrace();
return false; return false;
} }
PlotSquared.log(Captions.PREFIX.getTranslated() + "Loaded " + flagMap.size() logger.info("Loaded {} plot flag collections...", flagMap.size());
+ " plot flag collections..."); logger.info("Attempting to store these flags in the new table...");
PlotSquared.log(Captions.PREFIX.getTranslated()
+ "Attempting to store these flags in the new table...");
//
try (final PreparedStatement preparedStatement = this.connection.prepareStatement( try (final PreparedStatement preparedStatement = this.connection.prepareStatement(
"INSERT INTO `" + SQLManager.this.prefix "INSERT INTO `" + SQLManager.this.prefix
+ "plot_flags`(`plot_id`, `flag`, `value`) VALUES(?, ?, ?)")) { + "plot_flags`(`plot_id`, `flag`, `value`) VALUES(?, ?, ?)")) {
@ -1706,9 +1672,7 @@ public class SQLManager implements AbstractDB {
try { try {
preparedStatement.executeBatch(); preparedStatement.executeBatch();
} catch (final Exception e) { } catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated() logger.error("Failed to store flag values for plot with entry ID: {}", plotFlagEntry.getKey());
+ "Failed to store flag values for plot with entry ID: " + plotFlagEntry
.getKey());
e.printStackTrace(); e.printStackTrace();
continue; continue;
} }
@ -1716,19 +1680,14 @@ public class SQLManager implements AbstractDB {
if (System.currentTimeMillis() - timeStarted >= 1000L || plotsProcessed >= flagMap if (System.currentTimeMillis() - timeStarted >= 1000L || plotsProcessed >= flagMap
.size()) { .size()) {
timeStarted = System.currentTimeMillis(); timeStarted = System.currentTimeMillis();
PlotSquared.log( logger.info("... Flag conversion in progress. {}% done",
Captions.PREFIX.getTranslated() + "... Flag conversion in progress. " String.format("%.1f", ((float) flagsProcessed / totalFlags) * 100));
+ String.format("%.1f", ((float) flagsProcessed / totalFlags) * 100)
+ "% Done");
} }
PlotSquared.debug(Captions.PREFIX.getTranslated() logger.debug("- Finished converting flags for plot with entry ID: {}", plotFlagEntry.getKey());
+ "- Finished converting flags for plot with entry ID: " + plotFlagEntry
.getKey());
} }
} catch (final Exception e) { } catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "Failed to store flag values:"); logger.error("Failed to store flag values", e);
e.printStackTrace();
return false; return false;
} }
return true; return true;
@ -1820,9 +1779,8 @@ public class SQLManager implements AbstractDB {
time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(parsable) time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(parsable)
.getTime(); .getTime();
} catch (ParseException e) { } catch (ParseException e) {
PlotSquared.debug( logger.error("Could not parse date for plot: #{}({};{}) ({})",
"Could not parse date for plot: #" + id + "(" + areaID + ";" id, areaID, plot_id, parsable);
+ plot_id + ") (" + parsable + ")");
time = System.currentTimeMillis() + id; time = System.currentTimeMillis() + id;
} }
} }
@ -1836,9 +1794,8 @@ public class SQLManager implements AbstractDB {
if (Settings.Enabled_Components.DATABASE_PURGER) { if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(last.temp); toDelete.add(last.temp);
} else { } else {
PlotSquared.debug( logger.debug("Plot #{}({}) in `{}plot` is a duplicate."
"&cPLOT #" + id + "(" + last + ") in `" + this.prefix + " Delete this plot or set `database-purger: true` in the settings.yml", id, last, this.prefix);
+ "plot` is a duplicate. Delete this plot or set `database-purger: true` in the settings.yml.");
} }
} }
} else { } else {
@ -1869,9 +1826,8 @@ public class SQLManager implements AbstractDB {
} else if (Settings.Enabled_Components.DATABASE_PURGER) { } else if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(id); toDelete.add(id);
} else { } else {
PlotSquared.debug("&cENTRY #" + id + "(" + plot logger.debug("Entry #{}({}) in `plot_rating` does not exist."
+ ") in `plot_rating` does not exist. Create this plot or set `database-purger: true` in the " + " Create this plot or set `database-purger: true` in settings.yml", id, plot);
+ "settings.yml.");
} }
} }
deleteRows(toDelete, this.prefix + "plot_rating", "plot_plot_id"); deleteRows(toDelete, this.prefix + "plot_rating", "plot_plot_id");
@ -1898,9 +1854,8 @@ public class SQLManager implements AbstractDB {
} else if (Settings.Enabled_Components.DATABASE_PURGER) { } else if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(id); toDelete.add(id);
} else { } else {
PlotSquared.debug("&cENTRY #" + id + "(" + plot logger.debug("Entry #{}({}) in `plot_helpers` does not exist."
+ ") in `plot_helpers` does not exist. Create this plot or set `database-purger: true` in the settings" + " Create this plot or set `database-purger: true` in settings.yml", id, plot);
+ ".yml.");
} }
} }
deleteRows(toDelete, this.prefix + "plot_helpers", "plot_plot_id"); deleteRows(toDelete, this.prefix + "plot_helpers", "plot_plot_id");
@ -1926,9 +1881,8 @@ public class SQLManager implements AbstractDB {
} else if (Settings.Enabled_Components.DATABASE_PURGER) { } else if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(id); toDelete.add(id);
} else { } else {
PlotSquared.debug("&cENTRY #" + id + "(" + plot logger.debug("Entry #{}({}) in `plot_trusted` does not exist."
+ ") in `plot_trusted` does not exist. Create this plot or set `database-purger: true` in the settings" + " Create this plot or set `database-purger: true` in settings.yml", id, plot);
+ ".yml.");
} }
} }
deleteRows(toDelete, this.prefix + "plot_trusted", "plot_plot_id"); deleteRows(toDelete, this.prefix + "plot_trusted", "plot_plot_id");
@ -1954,8 +1908,8 @@ public class SQLManager implements AbstractDB {
} else if (Settings.Enabled_Components.DATABASE_PURGER) { } else if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(id); toDelete.add(id);
} else { } else {
PlotSquared.debug("&cENTRY " + id logger.debug("Entry #{}({}) in `plot_denied` does not exist."
+ " in `plot_denied` does not exist. Create this plot or set `database-purger: true` in the settings.yml."); + " Create this plot or set `database-purger: true` in settings.yml", id, plot);
} }
} }
deleteRows(toDelete, this.prefix + "plot_denied", "plot_plot_id"); deleteRows(toDelete, this.prefix + "plot_denied", "plot_plot_id");
@ -1976,19 +1930,16 @@ public class SQLManager implements AbstractDB {
final PlotFlag<?, ?> plotFlag = final PlotFlag<?, ?> plotFlag =
GlobalFlagContainer.getInstance().getFlagFromString(flag); GlobalFlagContainer.getInstance().getFlagFromString(flag);
if (plotFlag == null) { if (plotFlag == null) {
PlotSquared.debug("Adding unknown flag to plot with ID " + id); logger.debug("Adding unknown flag {} to plot with ID {}", flag, id);
plot.getFlagContainer().addUnknownFlag(flag, value); plot.getFlagContainer().addUnknownFlag(flag, value);
} else { } else {
try { try {
plot.getFlagContainer().addFlag(plotFlag.parse(value)); plot.getFlagContainer().addFlag(plotFlag.parse(value));
} catch (final FlagParseException e) { } catch (final FlagParseException e) {
e.printStackTrace(); e.printStackTrace();
PlotSquared logger.debug("Plot with ID {} has an invalid value:", id);
.debug("Plot with ID " + id + " has an invalid value:"); logger.debug("Failed to parse flag '{}', value '{}': {}",
PlotSquared.debug(Captions.FLAG_PARSE_ERROR.getTranslated() plotFlag.getName(), e.getValue(), e.getErrorMessage());
.replace("%flag_name%", plotFlag.getName())
.replace("%flag_value%", e.getValue())
.replace("%error%", e.getErrorMessage()));
if (!invalidFlags.containsKey(plot)) { if (!invalidFlags.containsKey(plot)) {
invalidFlags.put(plot, new ArrayList<>()); invalidFlags.put(plot, new ArrayList<>());
} }
@ -1998,8 +1949,8 @@ public class SQLManager implements AbstractDB {
} else if (Settings.Enabled_Components.DATABASE_PURGER) { } else if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(id); toDelete.add(id);
} else { } else {
PlotSquared.debug("&cPlot " + id logger.debug("Entry #{}({}) in `plot_flags` does not exist."
+ " in `plot_flags` does not exist. Create this plot or set `database-purger: true` in the settings.yml."); + " Create this plot or set `database-purger: true` in settings.yml", id, plot);
} }
} }
BlockTypeListFlag.skipCategoryVerification = BlockTypeListFlag.skipCategoryVerification =
@ -2008,9 +1959,8 @@ public class SQLManager implements AbstractDB {
for (final Map.Entry<Plot, Collection<PlotFlag<?, ?>>> plotFlagEntry : invalidFlags for (final Map.Entry<Plot, Collection<PlotFlag<?, ?>>> plotFlagEntry : invalidFlags
.entrySet()) { .entrySet()) {
for (final PlotFlag<?, ?> flag : plotFlagEntry.getValue()) { for (final PlotFlag<?, ?> flag : plotFlagEntry.getValue()) {
PlotSquared.debug("&cPlot \"" + plotFlagEntry.getKey() + "\"" logger.debug("Plot {} has an invalid flag ({}). A fix has been attempted",
+ " had an invalid flag (" + flag.getName() plotFlagEntry.getKey(), flag.getName());
+ "). A fix has been attempted.");
removeFlag(plotFlagEntry.getKey(), flag); removeFlag(plotFlagEntry.getKey(), flag);
} }
} }
@ -2052,9 +2002,8 @@ public class SQLManager implements AbstractDB {
} else if (Settings.Enabled_Components.DATABASE_PURGER) { } else if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(id); toDelete.add(id);
} else { } else {
PlotSquared.debug("&cENTRY #" + id + "(" + plot logger.debug("Entry #{}({}) in `plot_settings` does not exist."
+ ") in `plot_settings` does not exist. Create this plot or set `database-purger: true` in the settings" + " Create this plot or set `database-purger: true` in settings.yml", id, plot);
+ ".yml.");
} }
} }
deleteRows(toDelete, this.prefix + "plot_settings", "plot_plot_id"); deleteRows(toDelete, this.prefix + "plot_settings", "plot_plot_id");
@ -2070,16 +2019,14 @@ public class SQLManager implements AbstractDB {
for (Entry<String, AtomicInteger> entry : noExist.entrySet()) { for (Entry<String, AtomicInteger> entry : noExist.entrySet()) {
String worldName = entry.getKey(); String worldName = entry.getKey();
invalidPlot = true; invalidPlot = true;
PlotSquared.debug("&c[WARNING] Found " + entry.getValue().intValue() logger.debug("Warning! Found {} plots in DB for non existent world: '{}'",
+ " plots in DB for non existent world; '" + worldName + "'."); entry.getValue().intValue(), worldName);
} }
if (invalidPlot) { if (invalidPlot) {
PlotSquared.debug( logger.debug("Warning! Please create the world(s) or remove the plots using the purge command");
"&c[WARNING] - Please create the world/s or remove the plots using the purge command");
} }
} catch (SQLException e) { } catch (SQLException e) {
PlotSquared.debug("&7[WARN] Failed to load plots."); logger.error("Failed to load plots", e);
e.printStackTrace();
} }
return newPlots; return newPlots;
} }
@ -2120,9 +2067,7 @@ public class SQLManager implements AbstractDB {
preparedStatement.setInt(3, id2); preparedStatement.setInt(3, id2);
preparedStatement.execute(); preparedStatement.execute();
} catch (final Exception e) { } catch (final Exception e) {
PlotSquared.log( logger.error("Failed to persist wap of {} and {}", plot1, plot2);
Captions.PREFIX.getTranslated() + "Failed to persist swap of " + plot1 + " and "
+ plot2 + "!");
e.printStackTrace(); e.printStackTrace();
future.complete(false); future.complete(false);
return; return;
@ -2221,7 +2166,7 @@ public class SQLManager implements AbstractDB {
int last = -1; int last = -1;
for (int j = 0; j <= amount; j++) { for (int j = 0; j <= amount; j++) {
int purging = Math.max(j * packet, size); int purging = Math.max(j * packet, size);
PlotSquared.debug("Purging " + purging + " / " + size); logger.debug("Purging {}/{}", purging, size);
List<Integer> subList = List<Integer> subList =
uniqueIdsList.subList(j * packet, Math.min(size, (j + 1) * packet)); uniqueIdsList.subList(j * packet, Math.min(size, (j + 1) * packet));
if (subList.isEmpty()) { if (subList.isEmpty()) {
@ -2267,12 +2212,11 @@ public class SQLManager implements AbstractDB {
commit(); commit();
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); logger.error("Failed to purge plots", e);
PlotSquared.debug("&c[ERROR] FAILED TO PURGE PLOTS!");
return; return;
} }
} }
PlotSquared.debug("&6[INFO] SUCCESSFULLY PURGED " + uniqueIds.size() + " PLOTS!"); logger.debug("Successfully purged {} plots", uniqueIds.size());
} }
}); });
} }
@ -2295,8 +2239,8 @@ public class SQLManager implements AbstractDB {
} }
purgeIds(ids); purgeIds(ids);
} catch (SQLException e) { } catch (SQLException e) {
logger.error("Failed to purge area '{}'", area);
e.printStackTrace(); e.printStackTrace();
PlotSquared.debug("&c[ERROR] FAILED TO PURGE AREA '" + area + "'!");
} }
for (Iterator<PlotId> iterator = plots.iterator(); iterator.hasNext(); ) { for (Iterator<PlotId> iterator = plots.iterator(); iterator.hasNext(); ) {
PlotId plotId = iterator.next(); PlotId plotId = iterator.next();
@ -2774,8 +2718,8 @@ public class SQLManager implements AbstractDB {
if (cluster != null) { if (cluster != null) {
cluster.helpers.add(user); cluster.helpers.add(user);
} else { } else {
PlotSquared.debug("&cCluster #" + id + "(" + cluster logger.debug("Cluster #{}({}) in cluster_helpers does not exist."
+ ") in cluster_helpers does not exist. Please create the cluster or remove this entry."); + " Please create the cluster or remove this entry", id, cluster);
} }
} }
// Getting invited // Getting invited
@ -2793,8 +2737,8 @@ public class SQLManager implements AbstractDB {
if (cluster != null) { if (cluster != null) {
cluster.invited.add(user); cluster.invited.add(user);
} else { } else {
PlotSquared.debug("&cCluster #" + id + "(" + cluster logger.debug("Cluster #{}({}) in cluster_helpers does not exist."
+ ") in cluster_invited does not exist. Please create the cluster or remove this entry."); + " Please create the cluster or remove this entry", id, cluster);
} }
} }
resultSet = resultSet =
@ -2828,8 +2772,8 @@ public class SQLManager implements AbstractDB {
} }
cluster.settings.setMerged(merged); cluster.settings.setMerged(merged);
} else { } else {
PlotSquared.debug("&cCluster #" + id + "(" + cluster logger.debug("Cluster #{}({}) in cluster_helpers does not exist."
+ ") in cluster_settings does not exist. Please create the cluster or remove this entry."); + " Please create the cluster or remove this entry", id, cluster);
} }
} }
resultSet.close(); resultSet.close();
@ -2838,16 +2782,13 @@ public class SQLManager implements AbstractDB {
for (Entry<String, Integer> entry : noExist.entrySet()) { for (Entry<String, Integer> entry : noExist.entrySet()) {
String a = entry.getKey(); String a = entry.getKey();
invalidPlot = true; invalidPlot = true;
PlotSquared.debug("&c[WARNING] Found " + noExist.get(a) logger.debug("Warning! Found {} clusters in DB for non existent area; '{}'", noExist.get(a), a);
+ " clusters in DB for non existent area; '" + a + "'.");
} }
if (invalidPlot) { if (invalidPlot) {
PlotSquared.debug( logger.debug("Warning! Please create the world(s) or remove the clusters using the purge command");
"&c[WARNING] - Please create the world/s or remove the clusters using the purge command");
} }
} catch (SQLException e) { } catch (SQLException e) {
PlotSquared.debug("&7[WARN] Failed to load clusters."); logger.error("Failed to load clusters", e);
e.printStackTrace();
} }
return newClusters; return newClusters;
} }
@ -3039,8 +2980,7 @@ public class SQLManager implements AbstractDB {
if (!isValid()) { if (!isValid()) {
reconnect(); reconnect();
} }
PlotSquared.debug( logger.debug("All DB transactions during this session are being validated (This may take a while if corrections need to be made)");
"$1All DB transactions during this session are being validated (This may take a while if corrections need to be made)");
commit(); commit();
while (true) { while (true) {
if (!sendBatch()) { if (!sendBatch()) {
@ -3061,31 +3001,30 @@ public class SQLManager implements AbstractDB {
continue; continue;
} }
if (plot.getArea() == null) { if (plot.getArea() == null) {
PlotSquared.debug("CRITICAL ERROR IN VALIDATION TASK!"); logger.error("CRITICAL ERROR IN VALIDATION TASK!");
PlotSquared.debug("PLOT AREA CANNOT BE NULL! SKIPPING PLOT!"); logger.error("PLOT AREA CANNOT BE NULL! SKIPPING PLOT!");
continue; continue;
} }
if (database == null) { if (database == null) {
PlotSquared.debug("CRITICAL ERROR IN VALIDATION TASK!"); logger.error("CRITICAL ERROR IN VALIDATION TASK!");
PlotSquared.debug("DATABASE VARIABLE CANNOT BE NULL! NOW ENDING VALIDATION!!"); logger.error("DATABASE VARIABLE CANNOT BE NULL! NOW ENDING VALIDATION!");
break; break;
} }
HashMap<PlotId, Plot> worldPlots = database.get(plot.getArea().toString()); HashMap<PlotId, Plot> worldPlots = database.get(plot.getArea().toString());
if (worldPlots == null) { if (worldPlots == null) {
PlotSquared.debug("&8 - &7Creating plot (1): " + plot); logger.debug(" - Creating plot (1): {}", plot);
toCreate.add(plot); toCreate.add(plot);
continue; continue;
} }
Plot dataPlot = worldPlots.remove(plot.getId()); Plot dataPlot = worldPlots.remove(plot.getId());
if (dataPlot == null) { if (dataPlot == null) {
PlotSquared.debug("&8 - &7Creating plot (2): " + plot); logger.debug(" - Creating plot (2): {}", plot);
toCreate.add(plot); toCreate.add(plot);
continue; continue;
} }
// owner // owner
if (!plot.getOwnerAbs().equals(dataPlot.getOwnerAbs())) { if (!plot.getOwnerAbs().equals(dataPlot.getOwnerAbs())) {
PlotSquared.debug("&8 - &7Setting owner: " + plot + " -> " + MainUtil logger.debug(" - Setting owner: {} -> {}", plot, MainUtil.getName(plot.getOwnerAbs()));
.getName(plot.getOwnerAbs()));
setOwner(plot, plot.getOwnerAbs()); setOwner(plot, plot.getOwnerAbs());
} }
// trusted // trusted
@ -3094,9 +3033,7 @@ public class SQLManager implements AbstractDB {
HashSet<UUID> toRemove = (HashSet<UUID>) dataPlot.getTrusted().clone(); HashSet<UUID> toRemove = (HashSet<UUID>) dataPlot.getTrusted().clone();
toRemove.removeAll(plot.getTrusted()); toRemove.removeAll(plot.getTrusted());
toAdd.removeAll(dataPlot.getTrusted()); toAdd.removeAll(dataPlot.getTrusted());
PlotSquared.debug( logger.debug(" - Correcting {} trusted for: {}", toAdd.size() + toRemove.size(), plot);
"&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " trusted for: "
+ plot);
if (!toRemove.isEmpty()) { if (!toRemove.isEmpty()) {
for (UUID uuid : toRemove) { for (UUID uuid : toRemove) {
removeTrusted(plot, uuid); removeTrusted(plot, uuid);
@ -3113,9 +3050,7 @@ public class SQLManager implements AbstractDB {
HashSet<UUID> toRemove = (HashSet<UUID>) dataPlot.getMembers().clone(); HashSet<UUID> toRemove = (HashSet<UUID>) dataPlot.getMembers().clone();
toRemove.removeAll(plot.getMembers()); toRemove.removeAll(plot.getMembers());
toAdd.removeAll(dataPlot.getMembers()); toAdd.removeAll(dataPlot.getMembers());
PlotSquared.debug( logger.debug(" - Correcting {} members for: {}", toAdd.size() + toRemove.size());
"&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " members for: "
+ plot);
if (!toRemove.isEmpty()) { if (!toRemove.isEmpty()) {
for (UUID uuid : toRemove) { for (UUID uuid : toRemove) {
removeMember(plot, uuid); removeMember(plot, uuid);
@ -3132,9 +3067,7 @@ public class SQLManager implements AbstractDB {
HashSet<UUID> toRemove = (HashSet<UUID>) dataPlot.getDenied().clone(); HashSet<UUID> toRemove = (HashSet<UUID>) dataPlot.getDenied().clone();
toRemove.removeAll(plot.getDenied()); toRemove.removeAll(plot.getDenied());
toAdd.removeAll(dataPlot.getDenied()); toAdd.removeAll(dataPlot.getDenied());
PlotSquared.debug( logger.debug(" - Correcting {} denied for: {}", toAdd.size() + toRemove.size());
"&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " denied for: "
+ plot);
if (!toRemove.isEmpty()) { if (!toRemove.isEmpty()) {
for (UUID uuid : toRemove) { for (UUID uuid : toRemove) {
removeDenied(plot, uuid); removeDenied(plot, uuid);
@ -3149,7 +3082,7 @@ public class SQLManager implements AbstractDB {
boolean[] pm = plot.getMerged(); boolean[] pm = plot.getMerged();
boolean[] dm = dataPlot.getMerged(); boolean[] dm = dataPlot.getMerged();
if (pm[0] != dm[0] || pm[1] != dm[1]) { if (pm[0] != dm[0] || pm[1] != dm[1]) {
PlotSquared.debug(" - Correcting merge for: " + plot); logger.debug(" - Correcting merge for: {}", plot);
setMerged(dataPlot, plot.getMerged()); setMerged(dataPlot, plot.getMerged());
} }
Set<PlotFlag<?, ?>> pf = plot.getFlags(); Set<PlotFlag<?, ?>> pf = plot.getFlags();
@ -3157,7 +3090,6 @@ public class SQLManager implements AbstractDB {
if (!pf.isEmpty() && !df.isEmpty()) { if (!pf.isEmpty() && !df.isEmpty()) {
if (pf.size() != df.size() || !StringMan if (pf.size() != df.size() || !StringMan
.isEqual(StringMan.joinOrdered(pf, ","), StringMan.joinOrdered(df, ","))) { .isEqual(StringMan.joinOrdered(pf, ","), StringMan.joinOrdered(df, ","))) {
PlotSquared.debug(" - Correcting flags for: " + plot);
// setFlags(plot, pf); // setFlags(plot, pf);
// TODO: Re-implement // TODO: Re-implement
} }
@ -3168,8 +3100,7 @@ public class SQLManager implements AbstractDB {
HashMap<PlotId, Plot> map = entry.getValue(); HashMap<PlotId, Plot> map = entry.getValue();
if (!map.isEmpty()) { if (!map.isEmpty()) {
for (Entry<PlotId, Plot> entry2 : map.entrySet()) { for (Entry<PlotId, Plot> entry2 : map.entrySet()) {
PlotSquared.debug("$1Plot was deleted: " + entry2.getValue().toString() // TODO implement this when sure safe"
+ "// TODO implement this when sure safe");
} }
} }
} }

View File

@ -51,6 +51,8 @@ import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -59,7 +61,8 @@ import java.util.Locale;
public class HybridPlotWorld extends ClassicPlotWorld { public class HybridPlotWorld extends ClassicPlotWorld {
private static AffineTransform transform = new AffineTransform().rotateY(90); private static final Logger logger = LoggerFactory.getLogger(HybridPlotWorld.class);
private static final AffineTransform transform = new AffineTransform().rotateY(90);
public boolean ROAD_SCHEMATIC_ENABLED; public boolean ROAD_SCHEMATIC_ENABLED;
public boolean PLOT_SCHEMATIC = false; public boolean PLOT_SCHEMATIC = false;
public int PLOT_SCHEMATIC_HEIGHT = -1; public int PLOT_SCHEMATIC_HEIGHT = -1;
@ -158,13 +161,12 @@ public class HybridPlotWorld extends ClassicPlotWorld {
setupSchematics(); setupSchematics();
} catch (Exception event) { } catch (Exception event) {
event.printStackTrace(); event.printStackTrace();
PlotSquared.debug("&c - road schematics are disabled for this world."); logger.debug("- road schematics are disabled for this world");
} }
// Dump world settings // Dump world settings
if (Settings.DEBUG) { if (Settings.DEBUG) {
PlotSquared.debug(String.format("- Dumping settings for ClassicPlotWorld with name %s", logger.debug("- Dumping settings for ClassicPlotWorld with name {}", this.getWorldName());
this.getWorldName()));
final Field[] fields = this.getClass().getFields(); final Field[] fields = this.getClass().getFields();
for (final Field field : fields) { for (final Field field : fields) {
final String name = field.getName().toLowerCase(Locale.ENGLISH); final String name = field.getName().toLowerCase(Locale.ENGLISH);
@ -180,7 +182,7 @@ public class HybridPlotWorld extends ClassicPlotWorld {
} catch (final IllegalAccessException e) { } catch (final IllegalAccessException e) {
value = String.format("Failed to parse: %s", e.getMessage()); value = String.format("Failed to parse: %s", e.getMessage());
} }
PlotSquared.debug(String.format("-- %s = %s", name, value)); logger.debug("-- {} = {}", name, value);
} }
} }
} }
@ -360,7 +362,7 @@ public class HybridPlotWorld extends ClassicPlotWorld {
int pair = MathMan.pair(x, z); int pair = MathMan.pair(x, z);
BaseBlock[] existing = this.G_SCH.computeIfAbsent(pair, k -> new BaseBlock[height]); BaseBlock[] existing = this.G_SCH.computeIfAbsent(pair, k -> new BaseBlock[height]);
if (y >= height) { if (y >= height) {
PlotSquared.log("Error adding overlay block. `y > height` "); logger.error("Error adding overlay block. `y > height`");
return; return;
} }
existing[y] = id; existing[y] = id;

View File

@ -61,6 +61,8 @@ import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.BlockTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.util.ArrayDeque; import java.util.ArrayDeque;
@ -76,6 +78,8 @@ import java.util.concurrent.atomic.AtomicInteger;
public abstract class HybridUtils { public abstract class HybridUtils {
private static final Logger logger = LoggerFactory.getLogger(HybridUtils.class);
public static HybridUtils manager; public static HybridUtils manager;
public static Set<BlockVector2> regions; public static Set<BlockVector2> regions;
public static int height; public static int height;
@ -409,23 +413,23 @@ public abstract class HybridUtils {
iter.remove(); iter.remove();
boolean regenedRoad = regenerateRoad(area, chunk, extend); boolean regenedRoad = regenerateRoad(area, chunk, extend);
if (!regenedRoad) { if (!regenedRoad) {
PlotSquared.debug("Failed to regenerate roads."); logger.debug("Failed to regenerate roads");
} }
ChunkManager.manager.unloadChunk(area.getWorldName(), chunk, true); ChunkManager.manager.unloadChunk(area.getWorldName(), chunk, true);
} }
PlotSquared.debug("Cancelled road task"); logger.debug("Cancelled road task");
return; return;
} }
count.incrementAndGet(); count.incrementAndGet();
if (count.intValue() % 20 == 0) { if (count.intValue() % 20 == 0) {
PlotSquared.debug("PROGRESS: " + 100 * (2048 - chunks.size()) / 2048 + "%"); logger.info("Progress: {}%", 100 * (2048 - chunks.size()) / 2048);
} }
if (HybridUtils.regions.isEmpty() && chunks.isEmpty()) { if (HybridUtils.regions.isEmpty() && chunks.isEmpty()) {
PlotSquared.debug("Regenerating plot walls"); logger.debug("Regenerating plot walls");
regeneratePlotWalls(area); regeneratePlotWalls(area);
HybridUtils.UPDATE = false; HybridUtils.UPDATE = false;
PlotSquared.log("Finished road conversion"); logger.info("Finished road conversion");
// CANCEL TASK // CANCEL TASK
} else { } else {
final Runnable task = this; final Runnable task = this;
@ -437,11 +441,8 @@ public abstract class HybridUtils {
HybridUtils.regions.iterator(); HybridUtils.regions.iterator();
BlockVector2 loc = iterator.next(); BlockVector2 loc = iterator.next();
iterator.remove(); iterator.remove();
PlotSquared.debug( logger.debug("Updating .mcr: {}, {} (approx 1024 chunks)", loc.getX(), loc.getZ());
"Updating .mcr: " + loc.getX() + ", " + loc.getZ() logger.debug("- Remaining: {}", HybridUtils.regions.size());
+ " (approx 1024 chunks)");
PlotSquared
.debug(" - Remaining: " + HybridUtils.regions.size());
chunks.addAll(getChunks(loc)); chunks.addAll(getChunks(loc));
System.gc(); System.gc();
} }
@ -458,7 +459,7 @@ public abstract class HybridUtils {
boolean regenedRoads = boolean regenedRoads =
regenerateRoad(area, chunk, extend); regenerateRoad(area, chunk, extend);
if (!regenedRoads) { if (!regenedRoads) {
PlotSquared.debug("Failed to regenerate road."); logger.debug("Failed to regenerate road");
} }
} }
} }
@ -469,9 +470,8 @@ public abstract class HybridUtils {
Iterator<BlockVector2> iterator = HybridUtils.regions.iterator(); Iterator<BlockVector2> iterator = HybridUtils.regions.iterator();
BlockVector2 loc = iterator.next(); BlockVector2 loc = iterator.next();
iterator.remove(); iterator.remove();
PlotSquared.debug( logger.debug("Error! Could not update '{}/region/r.{}.{}.mca' (Corrupt chunk?)",
"[ERROR] Could not update '" + area.getWorldName() + "/region/r." area.getWorldHash(), loc.getX(), loc.getZ());
+ loc.getX() + "." + loc.getZ() + ".mca' (Corrupt chunk?)");
int sx = loc.getX() << 5; int sx = loc.getX() << 5;
int sz = loc.getZ() << 5; int sz = loc.getZ() << 5;
for (int x = sx; x < sx + 32; x++) { for (int x = sx; x < sx + 32; x++) {
@ -481,8 +481,7 @@ public abstract class HybridUtils {
true); true);
} }
} }
PlotSquared.debug(" - Potentially skipping 1024 chunks"); logger.debug("- Potentially skipping 1024 chunks");
PlotSquared.debug(" - TODO: recommend chunkster if corrupt");
} }
GlobalBlockQueue.IMP.addEmptyTask(() -> TaskManager.runTaskLater(task, 20)); GlobalBlockQueue.IMP.addEmptyTask(() -> TaskManager.runTaskLater(task, 20));
}); });

View File

@ -38,11 +38,14 @@ import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldedit.world.gamemode.GameModes; import com.sk89q.worldedit.world.gamemode.GameModes;
import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemType;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID; import java.util.UUID;
public class ConsolePlayer extends PlotPlayer<Actor> { public class ConsolePlayer extends PlotPlayer<Actor> {
private static final Logger logger = LoggerFactory.getLogger(ConsolePlayer.class);
private static ConsolePlayer instance; private static ConsolePlayer instance;
private ConsolePlayer() { private ConsolePlayer() {
@ -108,7 +111,7 @@ public class ConsolePlayer extends PlotPlayer<Actor> {
} }
@Override public void sendMessage(String message) { @Override public void sendMessage(String message) {
PlotSquared.log(message); logger.info(message);
} }
@Override public void teleport(Location location, TeleportCause cause) { @Override public void teleport(Location location, TeleportCause cause) {

View File

@ -25,7 +25,6 @@
*/ */
package com.plotsquared.core.util; package com.plotsquared.core.util;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.CaptionUtility; import com.plotsquared.core.configuration.CaptionUtility;
import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.ConfigurationSection; import com.plotsquared.core.configuration.ConfigurationSection;
@ -33,6 +32,8 @@ import com.plotsquared.core.player.ConsolePlayer;
import com.plotsquared.core.plot.BlockBucket; import com.plotsquared.core.plot.BlockBucket;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import lombok.NonNull; import lombok.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
@ -45,6 +46,7 @@ import java.util.Map;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class LegacyConverter { public final class LegacyConverter {
private static final Logger logger = LoggerFactory.getLogger(LegacyConverter.class);
public static final String CONFIGURATION_VERSION = "post_flattening"; public static final String CONFIGURATION_VERSION = "post_flattening";
private static final HashMap<String, ConfigurationType> TYPE_MAP = new HashMap<>(); private static final HashMap<String, ConfigurationType> TYPE_MAP = new HashMap<>();
@ -109,7 +111,7 @@ public final class LegacyConverter {
@NonNull final String key, @NonNull final String block) { @NonNull final String key, @NonNull final String block) {
final BlockBucket bucket = this.blockToBucket(block); final BlockBucket bucket = this.blockToBucket(block);
this.setString(section, key, bucket); this.setString(section, key, bucket);
PlotSquared.log(CaptionUtility logger.info(CaptionUtility
.format(ConsolePlayer.getConsole(), Captions.LEGACY_CONFIG_REPLACED.getTranslated(), .format(ConsolePlayer.getConsole(), Captions.LEGACY_CONFIG_REPLACED.getTranslated(),
block, bucket.toString())); block, bucket.toString()));
} }
@ -119,7 +121,7 @@ public final class LegacyConverter {
final BlockState[] blocks = this.splitBlockList(blockList); final BlockState[] blocks = this.splitBlockList(blockList);
final BlockBucket bucket = this.blockListToBucket(blocks); final BlockBucket bucket = this.blockListToBucket(blocks);
this.setString(section, key, bucket); this.setString(section, key, bucket);
PlotSquared.log(CaptionUtility logger.info(CaptionUtility
.format(ConsolePlayer.getConsole(), Captions.LEGACY_CONFIG_REPLACED.getTranslated(), .format(ConsolePlayer.getConsole(), Captions.LEGACY_CONFIG_REPLACED.getTranslated(),
plotBlockArrayString(blocks), bucket.toString())); plotBlockArrayString(blocks), bucket.toString()));
} }

View File

@ -56,6 +56,8 @@ import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -97,6 +99,7 @@ import java.util.stream.IntStream;
*/ */
public class MainUtil { public class MainUtil {
private static final Logger logger = LoggerFactory.getLogger(MainUtil.class);
private static final DecimalFormat FLAG_DECIMAL_FORMAT = new DecimalFormat("0"); private static final DecimalFormat FLAG_DECIMAL_FORMAT = new DecimalFormat("0");
static { static {
@ -516,11 +519,11 @@ public class MainUtil {
* @param message If a message should be sent to the player if a plot cannot be found * @param message If a message should be sent to the player if a plot cannot be found
* @return The plot if only 1 result is found, or null * @return The plot if only 1 result is found, or null
*/ */
@Nullable public static Plot getPlotFromString(PlotPlayer player, String arg, boolean message) { @Nullable public static Plot getPlotFromString(PlotPlayer<?> player, String arg, boolean message) {
if (arg == null) { if (arg == null) {
if (player == null) { if (player == null) {
if (message) { if (message) {
PlotSquared.log(Captions.NOT_VALID_PLOT_WORLD); logger.info("No plot area string was supplied");
} }
return null; return null;
} }
@ -643,7 +646,7 @@ public class MainUtil {
if (player == null) { if (player == null) {
String message = CaptionUtility String message = CaptionUtility
.format(null, (prefix ? Captions.PREFIX.getTranslated() : "") + msg); .format(null, (prefix ? Captions.PREFIX.getTranslated() : "") + msg);
PlotSquared.log(message); logger.info(message);
} else { } else {
player.sendMessage(CaptionUtility.format(player, player.sendMessage(CaptionUtility.format(player,
(prefix ? Captions.PREFIX.getTranslated() : "") + Captions.color(msg))); (prefix ? Captions.PREFIX.getTranslated() : "") + Captions.color(msg)));
@ -678,7 +681,7 @@ public class MainUtil {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(() -> {
String m = CaptionUtility.format(player, caption, args); String m = CaptionUtility.format(player, caption, args);
if (player == null) { if (player == null) {
PlotSquared.log(m); logger.info(m);
} else { } else {
player.sendMessage(m); player.sendMessage(m);
} }

View File

@ -36,6 +36,8 @@ import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.util.Collection; import java.util.Collection;
@ -44,6 +46,8 @@ import java.util.Set;
public abstract class RegionManager { public abstract class RegionManager {
private static final Logger logger = LoggerFactory.getLogger(RegionManager.class);
public static RegionManager manager = null; public static RegionManager manager = null;
public static BlockVector2 getRegion(Location location) { public static BlockVector2 getRegion(Location location) {
@ -141,7 +145,7 @@ public abstract class RegionManager {
world + File.separator + "region" + File.separator + "r." + loc.getX() + "." world + File.separator + "region" + File.separator + "r." + loc.getX() + "."
+ loc.getZ() + ".mca"; + loc.getZ() + ".mca";
File file = new File(PlotSquared.get().IMP.getWorldContainer(), directory); File file = new File(PlotSquared.get().IMP.getWorldContainer(), directory);
PlotSquared.log("&6 - Deleting file: " + file.getName() + " (max 1024 chunks)"); logger.info("- Deleting file: {} (max 1024 chunks)", file.getName());
if (file.exists()) { if (file.exists()) {
file.delete(); file.delete();
} }

View File

@ -33,6 +33,8 @@ import com.plotsquared.core.util.ThreadUtils;
import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.util.task.TaskManager;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -62,6 +64,8 @@ import java.util.function.Function;
*/ */
public class UUIDPipeline { public class UUIDPipeline {
private static final Logger logger = LoggerFactory.getLogger(UUIDPipeline.class);
private final Executor executor; private final Executor executor;
private final List<UUIDService> serviceList; private final List<UUIDService> serviceList;
private final List<Consumer<List<UUIDMapping>>> consumerList; private final List<Consumer<List<UUIDMapping>>> consumerList;
@ -164,7 +168,7 @@ public class UUIDPipeline {
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
e.printStackTrace(); e.printStackTrace();
} catch (TimeoutException ignored) { } catch (TimeoutException ignored) {
PlotSquared.log(Captions.PREFIX + " (UUID) Request for " + username + " timed out"); logger.warn("(UUID) Request for {} timed out", username);
// This is completely valid, we just don't care anymore // This is completely valid, we just don't care anymore
} }
return null; return null;
@ -187,7 +191,7 @@ public class UUIDPipeline {
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
e.printStackTrace(); e.printStackTrace();
} catch (TimeoutException ignored) { } catch (TimeoutException ignored) {
PlotSquared.log(Captions.PREFIX + " (UUID) Request for " + uuid + " timed out"); logger.warn("(UUID) Request for {} timed out", uuid);
// This is completely valid, we just don't care anymore // This is completely valid, we just don't care anymore
} }
return null; return null;
@ -321,7 +325,7 @@ public class UUIDPipeline {
this.consume(mappings); this.consume(mappings);
return mappings; return mappings;
} else if (Settings.DEBUG) { } else if (Settings.DEBUG) {
PlotSquared.log("Failed to find all usernames"); logger.debug("Failed to find all usernames");
} }
if (Settings.UUID.UNKNOWN_AS_DEFAULT) { if (Settings.UUID.UNKNOWN_AS_DEFAULT) {
@ -384,7 +388,7 @@ public class UUIDPipeline {
this.consume(mappings); this.consume(mappings);
return mappings; return mappings;
} else if (Settings.DEBUG) { } else if (Settings.DEBUG) {
PlotSquared.log("Failed to find all UUIDs"); logger.debug("Failed to find all UUIDs");
} }
throw new ServiceError("End of pipeline"); throw new ServiceError("End of pipeline");