Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Debug V3 Re-Write #158

Open
wants to merge 4 commits into
base: 2.6.2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/main/java/org/shanerx/tradeshop/data/config/Message.java
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ public final void sendItemMultiLineMessage(Player player, Map<Variable, List<Ite
boolean isJson = getString().startsWith("#json ");
String message = getPrefixed().replaceFirst("#json ", "");

Debug debug = TradeShop.getPlugin().getDebugger();
Debug debug = TradeShop.getPlugin().getVarManager().getDebugger();

for (Map.Entry<Variable, List<ItemStack>> entry : itemsToFill.entrySet()) {
Pattern pattern = Pattern.compile(MULTILINEREGEX.replace("&V&", entry.getKey().toString()));
Expand Down Expand Up @@ -367,7 +367,7 @@ public final void sendUserEditMultiLineMessage(Player player, Map<Variable, Map<
boolean isJson = getString().startsWith("#json ");
String message = getPrefixed().replaceFirst("#json ", "");

Debug debug = TradeShop.getPlugin().getDebugger();
Debug debug = TradeShop.getPlugin().getVarManager().getDebugger();

for (Map.Entry<Variable, Map<String, String>> entry : valuesToFill.entrySet()) {
Pattern pattern = Pattern.compile(MULTILINEREGEX.replace("&V&", entry.getKey().toString()));
Expand Down
31 changes: 22 additions & 9 deletions src/main/java/org/shanerx/tradeshop/data/config/Setting.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,19 @@ public enum Setting {
// PostComment " " adds single newline below setting and "\n" adds 2 newlines below
// PreComment `/n ` will have a new comment marker added after a sufficient space for proper formatting

CONFIG_VERSION(SettingSection.NONE, "config-version", 1.3),
CONFIG_VERSION(SettingSection.NONE, "config-version", 1.4),

// System Options
DATA_STORAGE_TYPE(SettingSection.SYSTEM_OPTIONS, "data-storage-type", "FLATFILE"),
MAX_SAVE_THREADS(SettingSection.SYSTEM_OPTIONS, "max-save-threads", 3),
ENABLE_DEBUG(SettingSection.SYSTEM_OPTIONS, "enable-debug", 0),
CHECK_UPDATES(SettingSection.SYSTEM_OPTIONS, "check-updates", true),
ALLOW_METRICS(SettingSection.SYSTEM_OPTIONS, "allow-metrics", true),
UNLIMITED_ADMIN(SettingSection.SYSTEM_OPTIONS, "unlimited-admin", false),

// ^ Debug Settings
DEBUG_TO_CONSOLE(SettingSection.DEBUG_SETTINGS, "debug-to-console", Collections.singletonList("Disabled")),
DEBUG_TO_FILE(SettingSection.DEBUG_SETTINGS, "debug-to-file", Collections.singletonList("Disabled")),

// ^ Logging
ENABLE_TRANSACTION_LOGGING(SettingSection.TRANSACTION_LOGGING_OPTIONS, "enable-transaction-logging", true),
OUTPUT_TYPE(SettingSection.TRANSACTION_LOGGING_OPTIONS, "output-type", "TSV"),
Expand Down Expand Up @@ -156,12 +159,7 @@ public static Setting findSetting(String search) {
static boolean upgrade() {
double version = CONFIG_VERSION.getDouble();
Set<Boolean> hasUpgraded = new HashSet<>(); // Uses this instead of a boolean to later replace below ifs with boolean return methods...
ConfigManager configManager = PLUGIN.getSettingManager();

// 2.2.2 Changed enable debug from true/false to integer
if (!configManager.getConfig().isInt(ENABLE_DEBUG.path)) {
ENABLE_DEBUG.clearSetting();
}
ConfigManager configManager = PLUGIN.getVarManager().getSettingManager();

// 2.2.2 Better Sorted/potentially commented config
if (version < 1.1) {
Expand Down Expand Up @@ -280,6 +278,17 @@ static boolean upgrade() {
version = 1.3;
}

if (version < 1.4) {

String oldKey = "system-options.enable-debug";
if (configManager.getConfig().contains(oldKey)) {
configManager.getConfig().set(oldKey, null);
hasUpgraded.add(true);
}

version = 1.4;
}

CONFIG_VERSION.setValue(version);

return hasUpgraded.contains(true);
Expand Down Expand Up @@ -380,7 +389,11 @@ public void setMappedValue(String subKey, Object obj) {
}

public void clearSetting() {
PLUGIN.getSettingManager().getConfig().set(getPath(), null);
setValue(null);
}

public void resetSetting() {
setValue(getDefaultValue());
}

public Object getSetting() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ public enum SettingSection {

NONE(0, ""),
SYSTEM_OPTIONS(1, "system-options"),
DEBUG_SETTINGS(50, SYSTEM_OPTIONS, "debug-settings"),

TRANSACTION_LOGGING_OPTIONS(50, SYSTEM_OPTIONS, "transaction-logging-options"),
TRANSACTION_LOGGING_OPTIONS(51, SYSTEM_OPTIONS, "transaction-logging-options"),

LANGUAGE_OPTIONS(2, "language-options"),
GLOBAL_OPTIONS(3, "global-options"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
Expand Down Expand Up @@ -233,7 +232,7 @@ public int getShopCountInWorld(World world) {
File folder = new File(TradeShop.getPlugin().getDataFolder().getAbsolutePath() + File.separator + "Data" + File.separator + worldName);
if (folder.exists() && folder.listFiles() != null) {
for (File file : folder.listFiles()) {
if (file.getName().contains(worldName))
if (file.getName().contains(worldName) && file.getName().endsWith(".json"))
count.addAndGet(new JsonShopData(ShopChunk.deserialize(file.getName().replace(".json", ""))).size());
}
}
Expand Down Expand Up @@ -287,7 +286,7 @@ protected ShopConfiguration getShopData(Chunk chunk) {
return getShopData(new ShopChunk(chunk));
}

private Map<String, JsonShopData> chunkDataCache = new HashMap<>();
private final Map<String, JsonShopData> chunkDataCache = new HashMap<>();
protected ShopConfiguration getShopData(ShopChunk chunk) {
if (dataType == DataType.FLATFILE) {
String serializedChunk = chunk.serialize();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ protected JsonConfiguration(String folderFromData, String fileName) {
}

// Caching File objects for synchronized(File) {} blocks
private static Map<String, File> fileCache = new HashMap<>();
private static final Map<String, File> fileCache = new HashMap<>();
public static File getFile(String folderFromData, String fileName) {
String path = getPath(folderFromData).getPath() + File.separator + fileName + ".json";

Expand Down Expand Up @@ -124,6 +124,7 @@ public static File[] getFilesInFolder(String folderFromData) {

protected void loadFile() {
try {
PLUGIN.getVarManager().getDebugger().log(String.join("\n", Files.readAllLines(file.toPath())), DebugLevels.JSON_LOADING, "JsonConfiguration#loadFile() - " + file.getName());
jsonObj = JsonParser.parseReader(new FileReader(file)).getAsJsonObject();

} catch (FileNotFoundException e) {
Expand All @@ -134,6 +135,8 @@ protected void loadFile() {
PLUGIN.getLogger().log(Level.SEVERE, "Could not load " + file.getName() + " file due to malformed Json! \n Please send the .err file with the same name to the TradeShop Devs. \n\nTradeShop will now disable, please remove/fix any err files before restarting the plugin.", e);

jsonSyntaxError(file, e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
import org.shanerx.tradeshop.shop.Shop;
import org.shanerx.tradeshop.shoplocation.ShopChunk;
import org.shanerx.tradeshop.shoplocation.ShopLocation;
import org.shanerx.tradeshop.utils.debug.Debug;
import org.shanerx.tradeshop.utils.debug.DebugLevels;
import org.shanerx.tradeshop.utils.gsonprocessing.GsonProcessor;

import java.io.File;
Expand All @@ -48,7 +50,11 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.logging.Level;
Expand Down Expand Up @@ -273,8 +279,10 @@ public void run() {
}

int expectedLength = str.getBytes(StandardCharsets.UTF_8).length;
Debug debug = Debug.findDebugger();

try {
debug.log(str, DebugLevels.JSON_SAVING, "JsonShopData^SaveThreadMaster#run().try-1 - " + file.getName());
if (file.exists()) {
bak.delete();
mjf.delete(); // Delete previous malformed and bak files to prevent conflicts with new ones. Could potentially rename with a counter if we really want to see a lot of malformed files.
Expand All @@ -297,6 +305,7 @@ public void run() {
}

fileBytes = chan.write(byteBuff);
debug.log(new String(byteBuff.asCharBuffer().array()), DebugLevels.JSON_SAVING, "JsonShopData^SaveThreadMaster#run().try-1_post-verify - " + file.getName());
chan.force(true);
chan.close();

Expand Down
137 changes: 109 additions & 28 deletions src/main/java/org/shanerx/tradeshop/utils/debug/Debug.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,58 +28,139 @@
import org.bukkit.Bukkit;
import org.shanerx.tradeshop.TradeShop;
import org.shanerx.tradeshop.data.config.Setting;
import org.shanerx.tradeshop.utils.objects.ObjectHolder;

import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.logging.Level;

public class Debug {
public abstract class Debug {

private final String PREFIX = "[TradeShop Debug%level%] ";
private int decimalDebugLevel;
private String binaryDebugLevel;
protected final String PREFIX;

public Debug() {
protected HashSet<DebugLevels> debugToConsole = new HashSet<>(),
debugToFile = new HashSet<>();

public Debug(int version) {
PREFIX = "[TradeShop Debug%V%%level%] ".replace("%V%", "V" + version);
reload();
}

public static Debug findDebugger() {
final TradeShop plugin = ((TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop"));
if (plugin != null) {
return plugin.getDebugger();
if (plugin == null) return null;

Debug debugger = plugin.getVarManager().getDebugger();
if (debugger != null) return debugger;

return newDebug();
}

/**
* @return true if the debug should be V3
*/
public static Optional<Boolean> detectDebugVersion() {
Optional<Boolean> v3 = Optional.empty();

ObjectHolder<Object> debugToConsole = new ObjectHolder<>(Setting.DEBUG_TO_CONSOLE.getSetting()),
debugToFile = new ObjectHolder<>(Setting.DEBUG_TO_FILE.getSetting());

if (debugToConsole.isNull()) {
Setting.DEBUG_TO_CONSOLE.resetSetting();
debugToConsole = new ObjectHolder<>(Setting.DEBUG_TO_CONSOLE.getSetting());
}

if (debugToFile.isNull()) {
Setting.DEBUG_TO_FILE.resetSetting();
debugToFile = new ObjectHolder<>(Setting.DEBUG_TO_FILE.getSetting());
}


boolean debugToConsoleAsList = debugToConsole.asStringList().orElse(Collections.emptyList()).isEmpty(),
debugToFileAsList = debugToFile.isList() && debugToFile.asStringList().orElse(Collections.emptyList()).isEmpty(),
debugToConsoleAsInt = debugToConsole.isInteger() && debugToConsole.asInteger() == 0,
debugToFileAsInt = debugToFile.isInteger() && debugToFile.asInteger() == 0;

if (debugToConsole.isInteger() && debugToFile.isInteger()) {
v3 = Optional.of(true);
} else if (debugToConsole.isList() && debugToFile.isList()) {
v3 = Optional.of(true);
} else if (debugToConsoleAsList || debugToFileAsList || debugToConsoleAsInt || debugToFileAsInt) {
if (debugToConsoleAsInt || debugToConsoleAsList) {
v3 = Optional.of(debugToFile.isList());
} else {
v3 = Optional.of(debugToConsole.isList());
}
}
return v3;
}

public static Debug newDebug() {
Optional<Boolean> debugVersion = detectDebugVersion();
if (debugVersion.isPresent()) {
return debugVersion.get() ? new DebugV3() : new DebugV2();
} else {
return new Debug();
Setting.DEBUG_TO_CONSOLE.resetSetting();
Setting.DEBUG_TO_FILE.resetSetting();
return new DebugV3();
}
}

public void reload() {
decimalDebugLevel = Setting.ENABLE_DEBUG.getInt();
if (decimalDebugLevel < 0) {
decimalDebugLevel = DebugLevels.maxValue();
if (loadDebugLevel(Setting.DEBUG_TO_CONSOLE, debugToConsole)) {
Bukkit.getLogger().log(Level.INFO, PREFIX.replace("%level%", "") + "Console Debugging enabled!");
Bukkit.getLogger().log(Level.INFO, PREFIX.replace("%level%", "") + "Enabled debuggers: " + debugToConsole.toString());
}
StringBuilder sb = new StringBuilder(Integer.toBinaryString(decimalDebugLevel));
while (sb.length() < DebugLevels.levels())
sb.insert(0, 0);

binaryDebugLevel = sb.reverse().toString();
if (loadDebugLevel(Setting.DEBUG_TO_FILE, debugToFile)) {
Bukkit.getLogger().log(Level.INFO, PREFIX.replace("%level%", "") + "File Debugging enabled!");
Bukkit.getLogger().log(Level.INFO, PREFIX.replace("%level%", "") + "Enabled debuggers: " + debugToFile.toString());
}
}

/**
* @return true if debugging is enabled
* @implNote This method is called by {@link #reload()} to load the debug level. It should add enums from DebugLevels to the {@link HashSet} specified by debugDestination to enable debugging for each item.
* @var debugDestination The {@link HashSet} to add the debug levels to
* @var settingToReadFrom The {@link Setting} to read the debug level from
*/
public abstract boolean loadDebugLevel(Setting settingToReadFrom, HashSet<DebugLevels> debugDestination);

if (decimalDebugLevel > 0) {
Bukkit.getLogger().log(Level.INFO, PREFIX.replace("%level%", "") + "Debugging enabled!");
Bukkit.getLogger().log(Level.INFO, PREFIX.replace("%level%", "") + "Decimal Debug level: " + decimalDebugLevel);
Bukkit.getLogger().log(Level.INFO, PREFIX.replace("%level%", "") + "Debug levels: " + binaryDebugLevel);
}
public String getFormattedPrefix(DebugLevels debugLevel) {
return PREFIX.replace("%level%", debugLevel.getPrefix());
}

public void log(String message, DebugLevels level) {
if (level.getPosition() > 0 && binaryDebugLevel.charAt(level.getPosition() - 1) == '1') {
Bukkit.getLogger().log(level.getLogLevel(), PREFIX.replace("%level%", level.getPrefix()) + message);
log(message, level, null);
}

public void log(String message, DebugLevels level, String positionalNote) {
StringBuilder messageBuilder = new StringBuilder();

if (debugToConsole.contains(level)) {
message = PREFIX.replace("%level%", level.getPrefix()) + message;
} else if (level == DebugLevels.DISABLED) {
Bukkit.getLogger().log(level.getLogLevel(), PREFIX.replace(" Debug%level%", "") + message);
message = PREFIX.replaceAll("( Debug.%level%)", "") + message;
} else if (level.getPosition() < 0) {
Bukkit.getLogger().log(level.getLogLevel(), PREFIX.replace("%level%", level.getPrefix()) + message);
message = PREFIX.replace("%level%", level.getPrefix()) + message;
}

if (positionalNote != null && !positionalNote.isEmpty()) {
messageBuilder.append("{ ").append(level.getPrefix()).append(" }\n");
}

messageBuilder.append(message);

if (debugToConsole.contains(level)) logToConsole(level.getLogLevel(), messageBuilder.toString());
if (debugToFile.contains(level)) logToFile(level.getLogLevel(), messageBuilder.toString());
}

public String getFormattedPrefix(DebugLevels debugLevel) {
return PREFIX.replace("%level%", debugLevel.getPrefix());
private void logToConsole(Level level, String message) {
Bukkit.getLogger().log(level, message);
}

private void logToFile(Level level, String message) {
Bukkit.getLogger().log(level, "\n----- LOGTOFILE -----" + message + "\n----- END LOGTOFILE -----\n"); //TODO: Add file logging
SparklingComet marked this conversation as resolved.
Show resolved Hide resolved
}
}

}
18 changes: 16 additions & 2 deletions src/main/java/org/shanerx/tradeshop/utils/debug/DebugLevels.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

package org.shanerx.tradeshop.utils.debug;

import java.util.Optional;
import java.util.logging.Level;

public enum DebugLevels {
Expand All @@ -46,8 +47,9 @@ public enum DebugLevels {
SQLITE(12, Level.INFO), // 2048
GSON(13, Level.INFO), // 4096
DATA_VERIFICATION(14, Level.INFO), // 8192
FIND_COMMAND(15, Level.INFO) // 16384

FIND_COMMAND(15, Level.INFO), // 16384
JSON_SAVING(16, Level.INFO), // 32768
JSON_LOADING(17, Level.INFO) // 65536

;

Expand Down Expand Up @@ -88,4 +90,16 @@ public String getPrefix() {
return " - " + name();
}

public static Optional<DebugLevels> match(String desiredLevel) {
Optional<DebugLevels> ret = Optional.empty();
for (DebugLevels level : values()) {
if (level.name().replaceAll("\\w", "").equalsIgnoreCase(desiredLevel)) {
ret = Optional.of(level);
break;
}
}

return ret;
}

}
Loading