Moved Static variables to separate class (Statics)

Created custom logger (based on ModLogger by Cotton)
Removed info & sendError methods form Utilities (Moved to CustomLogger)
2.x-1.16
szymon 2020-08-05 19:11:06 +02:00
parent a4fde82b84
commit 7738e54583
24 changed files with 292 additions and 224 deletions

View File

@ -9,6 +9,6 @@ loader_version=0.9.0+build.204
fabric_version=0.16.2+build.385-1.16.1 fabric_version=0.16.2+build.385-1.16.1
# Mod Properties # Mod Properties
mod_version = 1.4.0 mod_version = 2.0.0
maven_group = net.szum123321 maven_group = net.szum123321
archives_base_name = textile_backup archives_base_name = textile_backup

View File

@ -26,7 +26,7 @@ import java.util.HashSet;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
@ConfigFile(name = TextileBackup.MOD_ID) @ConfigFile(name = Statics.MOD_ID)
public class ConfigHandler { public class ConfigHandler {
@Comment("\nTime between automatic backups in seconds\n" + @Comment("\nTime between automatic backups in seconds\n" +
"When set to 0 backups will not be performed automatically\n") "When set to 0 backups will not be performed automatically\n")

View File

@ -0,0 +1,22 @@
package net.szum123321.textile_backup;
import net.szum123321.textile_backup.core.CustomLogger;
import net.szum123321.textile_backup.core.create.BackupScheduler;
import net.szum123321.textile_backup.core.restore.AwaitThread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
public class Statics {
public static final String MOD_ID = "textile_backup";
public static final String MOD_NAME = "Textile Backup";
public static final CustomLogger LOGGER = new CustomLogger(MOD_ID, MOD_NAME);
public static ConfigHandler CONFIG;
public static final BackupScheduler scheduler = new BackupScheduler();
public static ExecutorService executorService = Executors.newSingleThreadExecutor();
public static final AtomicBoolean globalShutdownBackupFlag = new AtomicBoolean(true);
public static AwaitThread restoreAwaitThread;
}

View File

@ -21,7 +21,6 @@ package net.szum123321.textile_backup;
import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import io.github.cottonmc.cotton.config.ConfigManager; import io.github.cottonmc.cotton.config.ConfigManager;
import io.github.cottonmc.cotton.logging.ModLogger;
import net.fabricmc.api.ModInitializer; import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback; import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
@ -34,60 +33,42 @@ import net.szum123321.textile_backup.commands.permission.WhitelistCommand;
import net.szum123321.textile_backup.commands.restore.KillRestoreCommand; import net.szum123321.textile_backup.commands.restore.KillRestoreCommand;
import net.szum123321.textile_backup.commands.restore.ListBackupsCommand; import net.szum123321.textile_backup.commands.restore.ListBackupsCommand;
import net.szum123321.textile_backup.commands.restore.RestoreBackupCommand; import net.szum123321.textile_backup.commands.restore.RestoreBackupCommand;
import net.szum123321.textile_backup.core.create.BackupScheduler;
import net.szum123321.textile_backup.core.restore.AwaitThread;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessageFactory;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
public class TextileBackup implements ModInitializer { public class TextileBackup implements ModInitializer {
public static final String MOD_ID = "textile_backup";
public static final Logger LOGGER = LogManager.getLogger("Textile Backup", ParameterizedMessageFactory.INSTANCE);
public static ConfigHandler CONFIG;
public static final BackupScheduler scheduler = new BackupScheduler();
public static ExecutorService executorService = Executors.newSingleThreadExecutor();
public static final AtomicBoolean globalShutdownBackupFlag = new AtomicBoolean(true);
public static AwaitThread restoreAwaitThread;
@Override @Override
public void onInitialize() { public void onInitialize() {
CONFIG = ConfigManager.loadConfig(ConfigHandler.class); Statics.LOGGER.info("Starting Textile Backup by Szum123321.");
Optional<String> errorMessage = CONFIG.sanitize(); Statics.CONFIG = ConfigManager.loadConfig(ConfigHandler.class);
Optional<String> errorMessage = Statics.CONFIG.sanitize();
if(errorMessage.isPresent()) { if(errorMessage.isPresent()) {
LOGGER.fatal("TextileBackup config file has wrong settings! \n {}", errorMessage.get()); Statics.LOGGER.fatal("TextileBackup config file has wrong settings! \n {}", errorMessage.get());
System.exit(1); System.exit(1);
} }
if(TextileBackup.CONFIG.backupInterval > 0) if(Statics.CONFIG.backupInterval > 0)
ServerTickEvents.END_SERVER_TICK.register(scheduler::tick); ServerTickEvents.END_SERVER_TICK.register(Statics.scheduler::tick);
ServerLifecycleEvents.SERVER_STARTING.register(ignored -> { ServerLifecycleEvents.SERVER_STARTING.register(ignored -> {
if(executorService.isShutdown()) if(Statics.executorService.isShutdown())
executorService = Executors.newSingleThreadExecutor(); Statics.executorService = Executors.newSingleThreadExecutor();
}); });
ServerLifecycleEvents.SERVER_STOPPED.register(ignored -> executorService.shutdown()); ServerLifecycleEvents.SERVER_STOPPED.register(ignored -> Statics.executorService.shutdown());
CommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> dispatcher.register( CommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> dispatcher.register(
LiteralArgumentBuilder.<ServerCommandSource>literal("backup") LiteralArgumentBuilder.<ServerCommandSource>literal("backup")
.requires((ctx) -> { .requires((ctx) -> {
try { try {
return ((CONFIG.playerWhitelist.contains(ctx.getEntityOrThrow().getEntityName()) || return ((Statics.CONFIG.playerWhitelist.contains(ctx.getEntityOrThrow().getEntityName()) ||
ctx.hasPermissionLevel(CONFIG.permissionLevel)) && ctx.hasPermissionLevel(Statics.CONFIG.permissionLevel)) &&
!CONFIG.playerBlacklist.contains(ctx.getEntityOrThrow().getEntityName())) || !Statics.CONFIG.playerBlacklist.contains(ctx.getEntityOrThrow().getEntityName())) ||
(ctx.getMinecraftServer().isSinglePlayer() && (ctx.getMinecraftServer().isSinglePlayer() &&
CONFIG.alwaysSingleplayerAllowed); Statics.CONFIG.alwaysSingleplayerAllowed);
} catch (Exception ignored) { //Command was called from server console. } catch (Exception ignored) { //Command was called from server console.
return true; return true;
} }

View File

@ -23,7 +23,7 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import net.minecraft.server.command.CommandManager; import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.create.BackupContext; import net.szum123321.textile_backup.core.create.BackupContext;
import net.szum123321.textile_backup.core.create.BackupHelper; import net.szum123321.textile_backup.core.create.BackupHelper;
@ -36,8 +36,8 @@ public class StartBackupCommand {
} }
private static int executeWithComment(CommandContext<ServerCommandSource> ctx) { private static int executeWithComment(CommandContext<ServerCommandSource> ctx) {
if(!TextileBackup.executorService.isShutdown()) if(!Statics.executorService.isShutdown())
TextileBackup.executorService.submit( Statics.executorService.submit(
BackupHelper.create( BackupHelper.create(
new BackupContext.Builder() new BackupContext.Builder()
.setCommandSource(ctx.getSource()) .setCommandSource(ctx.getSource())
@ -53,8 +53,8 @@ public class StartBackupCommand {
} }
private static int execute(ServerCommandSource source){ private static int execute(ServerCommandSource source){
if(!TextileBackup.executorService.isShutdown()) if(!Statics.executorService.isShutdown())
TextileBackup.executorService.submit( Statics.executorService.submit(
BackupHelper.create( BackupHelper.create(
new BackupContext.Builder() new BackupContext.Builder()
.setCommandSource(source) .setCommandSource(source)

View File

@ -10,8 +10,7 @@ import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.LiteralText; import net.minecraft.text.LiteralText;
import net.minecraft.text.TranslatableText; import net.minecraft.text.TranslatableText;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.Utilities;
public class BlacklistCommand { public class BlacklistCommand {
public static LiteralArgumentBuilder<ServerCommandSource> register() { public static LiteralArgumentBuilder<ServerCommandSource> register() {
@ -40,7 +39,7 @@ public class BlacklistCommand {
builder.append("Currently on the blacklist are: "); builder.append("Currently on the blacklist are: ");
for(String name : TextileBackup.CONFIG.playerBlacklist){ for(String name : Statics.CONFIG.playerBlacklist){
builder.append(name); builder.append(name);
builder.append(", "); builder.append(", ");
} }
@ -53,11 +52,11 @@ public class BlacklistCommand {
private static int executeAdd(CommandContext<ServerCommandSource> ctx) throws CommandSyntaxException { private static int executeAdd(CommandContext<ServerCommandSource> ctx) throws CommandSyntaxException {
ServerPlayerEntity player = EntityArgumentType.getPlayer(ctx, "player"); ServerPlayerEntity player = EntityArgumentType.getPlayer(ctx, "player");
if(TextileBackup.CONFIG.playerBlacklist.contains(player.getEntityName())) { if(Statics.CONFIG.playerBlacklist.contains(player.getEntityName())) {
ctx.getSource().sendFeedback(new TranslatableText("Player: %s is already blacklisted.", player.getEntityName()), false); ctx.getSource().sendFeedback(new TranslatableText("Player: %s is already blacklisted.", player.getEntityName()), false);
}else{ }else{
TextileBackup.CONFIG.playerBlacklist.add(player.getEntityName()); Statics.CONFIG.playerBlacklist.add(player.getEntityName());
ConfigManager.saveConfig(TextileBackup.CONFIG); ConfigManager.saveConfig(Statics.CONFIG);
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
@ -65,8 +64,8 @@ public class BlacklistCommand {
builder.append(player.getEntityName()); builder.append(player.getEntityName());
builder.append(" added to the blacklist"); builder.append(" added to the blacklist");
if(TextileBackup.CONFIG.playerWhitelist.contains(player.getEntityName())){ if(Statics.CONFIG.playerWhitelist.contains(player.getEntityName())){
TextileBackup.CONFIG.playerWhitelist.remove(player.getEntityName()); Statics.CONFIG.playerWhitelist.remove(player.getEntityName());
builder.append(" and removed form the whitelist"); builder.append(" and removed form the whitelist");
} }
@ -74,7 +73,7 @@ public class BlacklistCommand {
ctx.getSource().getMinecraftServer().getCommandManager().sendCommandTree(player); ctx.getSource().getMinecraftServer().getCommandManager().sendCommandTree(player);
Utilities.info(builder.toString(), ctx.getSource()); Statics.LOGGER.sendInfo(ctx.getSource(), builder.toString());
} }
return 1; return 1;
@ -83,11 +82,11 @@ public class BlacklistCommand {
private static int executeRemove(CommandContext<ServerCommandSource> ctx) throws CommandSyntaxException { private static int executeRemove(CommandContext<ServerCommandSource> ctx) throws CommandSyntaxException {
ServerPlayerEntity player = EntityArgumentType.getPlayer(ctx, "player"); ServerPlayerEntity player = EntityArgumentType.getPlayer(ctx, "player");
if(!TextileBackup.CONFIG.playerBlacklist.contains(player.getEntityName())) { if(!Statics.CONFIG.playerBlacklist.contains(player.getEntityName())) {
ctx.getSource().sendFeedback(new TranslatableText("Player: %s newer was blacklisted.", player.getEntityName()), false); ctx.getSource().sendFeedback(new TranslatableText("Player: %s newer was blacklisted.", player.getEntityName()), false);
}else{ }else{
TextileBackup.CONFIG.playerBlacklist.remove(player.getEntityName()); Statics.CONFIG.playerBlacklist.remove(player.getEntityName());
ConfigManager.saveConfig(TextileBackup.CONFIG); ConfigManager.saveConfig(Statics.CONFIG);
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
@ -97,7 +96,7 @@ public class BlacklistCommand {
ctx.getSource().getMinecraftServer().getCommandManager().sendCommandTree(player); ctx.getSource().getMinecraftServer().getCommandManager().sendCommandTree(player);
Utilities.info(builder.toString(), ctx.getSource()); Statics.LOGGER.sendInfo(ctx.getSource(), builder.toString());
} }
return 1; return 1;

View File

@ -10,8 +10,7 @@ import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.LiteralText; import net.minecraft.text.LiteralText;
import net.minecraft.text.TranslatableText; import net.minecraft.text.TranslatableText;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.Utilities;
public class WhitelistCommand { public class WhitelistCommand {
public static LiteralArgumentBuilder<ServerCommandSource> register(){ public static LiteralArgumentBuilder<ServerCommandSource> register(){
@ -40,7 +39,7 @@ public class WhitelistCommand {
builder.append("Currently on the whitelist are: "); builder.append("Currently on the whitelist are: ");
for(String name : TextileBackup.CONFIG.playerWhitelist){ for(String name : Statics.CONFIG.playerWhitelist){
builder.append(name); builder.append(name);
builder.append(", "); builder.append(", ");
} }
@ -53,11 +52,11 @@ public class WhitelistCommand {
private static int executeAdd(CommandContext<ServerCommandSource> ctx) throws CommandSyntaxException { private static int executeAdd(CommandContext<ServerCommandSource> ctx) throws CommandSyntaxException {
ServerPlayerEntity player = EntityArgumentType.getPlayer(ctx, "player"); ServerPlayerEntity player = EntityArgumentType.getPlayer(ctx, "player");
if(TextileBackup.CONFIG.playerWhitelist.contains(player.getEntityName())) { if(Statics.CONFIG.playerWhitelist.contains(player.getEntityName())) {
ctx.getSource().sendFeedback(new TranslatableText("Player: %s is already whitelisted.", player.getEntityName()), false); ctx.getSource().sendFeedback(new TranslatableText("Player: %s is already whitelisted.", player.getEntityName()), false);
}else{ }else{
TextileBackup.CONFIG.playerWhitelist.add(player.getEntityName()); Statics.CONFIG.playerWhitelist.add(player.getEntityName());
ConfigManager.saveConfig(TextileBackup.CONFIG); ConfigManager.saveConfig(Statics.CONFIG);
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
@ -65,8 +64,8 @@ public class WhitelistCommand {
builder.append(player.getEntityName()); builder.append(player.getEntityName());
builder.append(" added to the whitelist"); builder.append(" added to the whitelist");
if(TextileBackup.CONFIG.playerBlacklist.contains(player.getEntityName())){ if(Statics.CONFIG.playerBlacklist.contains(player.getEntityName())){
TextileBackup.CONFIG.playerBlacklist.remove(player.getEntityName()); Statics.CONFIG.playerBlacklist.remove(player.getEntityName());
builder.append(" and removed form the blacklist"); builder.append(" and removed form the blacklist");
} }
@ -74,7 +73,7 @@ public class WhitelistCommand {
ctx.getSource().getMinecraftServer().getCommandManager().sendCommandTree(player); ctx.getSource().getMinecraftServer().getCommandManager().sendCommandTree(player);
Utilities.info(builder.toString(), ctx.getSource()); Statics.LOGGER.sendInfo(ctx.getSource(), builder.toString());
} }
return 1; return 1;
@ -83,11 +82,11 @@ public class WhitelistCommand {
private static int executeRemove(CommandContext<ServerCommandSource> ctx) throws CommandSyntaxException { private static int executeRemove(CommandContext<ServerCommandSource> ctx) throws CommandSyntaxException {
ServerPlayerEntity player = EntityArgumentType.getPlayer(ctx, "player"); ServerPlayerEntity player = EntityArgumentType.getPlayer(ctx, "player");
if(!TextileBackup.CONFIG.playerWhitelist.contains(player.getEntityName())) { if(!Statics.CONFIG.playerWhitelist.contains(player.getEntityName())) {
ctx.getSource().sendFeedback(new TranslatableText("Player: %s newer was on the whitelist.", player.getEntityName()), false); ctx.getSource().sendFeedback(new TranslatableText("Player: %s newer was on the whitelist.", player.getEntityName()), false);
}else{ }else{
TextileBackup.CONFIG.playerWhitelist.remove(player.getEntityName()); Statics.CONFIG.playerWhitelist.remove(player.getEntityName());
ConfigManager.saveConfig(TextileBackup.CONFIG); ConfigManager.saveConfig(Statics.CONFIG);
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append("Player: "); builder.append("Player: ");
@ -96,7 +95,7 @@ public class WhitelistCommand {
ctx.getSource().getMinecraftServer().getCommandManager().sendCommandTree(player); ctx.getSource().getMinecraftServer().getCommandManager().sendCommandTree(player);
Utilities.info(builder.toString(), ctx.getSource()); Statics.LOGGER.sendInfo(ctx.getSource(), builder.toString());
} }
return 1; return 1;

View File

@ -4,14 +4,14 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.server.command.CommandManager; import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.text.LiteralText; import net.minecraft.text.LiteralText;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
public class KillRestoreCommand { public class KillRestoreCommand {
public static LiteralArgumentBuilder<ServerCommandSource> register() { public static LiteralArgumentBuilder<ServerCommandSource> register() {
return CommandManager.literal("kill_r") //TODO: come up with something better return CommandManager.literal("kill_r") //TODO: come up with something better
.executes(ctx -> { .executes(ctx -> {
if(TextileBackup.restoreAwaitThread != null && TextileBackup.restoreAwaitThread.isRunning()) { if(Statics.restoreAwaitThread != null && Statics.restoreAwaitThread.isAlive()) {
TextileBackup.restoreAwaitThread.kill(); Statics.restoreAwaitThread.interrupt();
ctx.getSource().sendFeedback(new LiteralText("Backup restoration successfully stopped"), false); ctx.getSource().sendFeedback(new LiteralText("Backup restoration successfully stopped"), false);
} else { } else {
ctx.getSource().sendFeedback(new LiteralText("Failed to stop backup restoration"), false); ctx.getSource().sendFeedback(new LiteralText("Failed to stop backup restoration"), false);

View File

@ -12,7 +12,7 @@ import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.text.LiteralText; import net.minecraft.text.LiteralText;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.restore.AwaitThread; import net.szum123321.textile_backup.core.restore.AwaitThread;
import net.szum123321.textile_backup.core.restore.RestoreHelper; import net.szum123321.textile_backup.core.restore.RestoreHelper;
@ -41,18 +41,18 @@ public class RestoreBackupCommand {
LocalDateTime dateTime = LocalDateTime.from(dateTimeFormatter.parse(file)); LocalDateTime dateTime = LocalDateTime.from(dateTimeFormatter.parse(file));
if(ctx.getSource().getEntity() != null) if(ctx.getSource().getEntity() != null)
TextileBackup.LOGGER.info("Backup restoration was initiated by: {}", ctx.getSource().getName()); Statics.LOGGER.info("Backup restoration was initiated by: {}", ctx.getSource().getName());
else else
TextileBackup.LOGGER.info("Backup restoration was initiated form Server Console"); Statics.LOGGER.info("Backup restoration was initiated form Server Console");
if(TextileBackup.restoreAwaitThread == null || !TextileBackup.restoreAwaitThread.isRunning()) { if(Statics.restoreAwaitThread == null || !Statics.restoreAwaitThread.isAlive()) {
TextileBackup.restoreAwaitThread = new AwaitThread( Statics.restoreAwaitThread = new AwaitThread(
TextileBackup.CONFIG.restoreDelay, Statics.CONFIG.restoreDelay,
RestoreHelper.create(dateTime, ctx.getSource().getMinecraftServer(), null) RestoreHelper.create(dateTime, ctx.getSource().getMinecraftServer(), null)
); );
TextileBackup.restoreAwaitThread.start(); Statics.restoreAwaitThread.start();
} else if(TextileBackup.restoreAwaitThread != null && TextileBackup.restoreAwaitThread.isRunning()) { } else if(Statics.restoreAwaitThread != null && Statics.restoreAwaitThread.isAlive()) {
ctx.getSource().sendFeedback(new LiteralText("Someone has already started another restoration."), false); ctx.getSource().sendFeedback(new LiteralText("Someone has already started another restoration."), false);
} }
@ -66,18 +66,18 @@ public class RestoreBackupCommand {
LocalDateTime dateTime = LocalDateTime.from(dateTimeFormatter.parse(file)); LocalDateTime dateTime = LocalDateTime.from(dateTimeFormatter.parse(file));
if(ctx.getSource().getEntity() != null) if(ctx.getSource().getEntity() != null)
TextileBackup.LOGGER.info("Backup restoration was initiated by: {}", ctx.getSource().getName()); Statics.LOGGER.info("Backup restoration was initiated by: {}", ctx.getSource().getName());
else else
TextileBackup.LOGGER.info("Backup restoration was initiated form Server Console"); Statics.LOGGER.info("Backup restoration was initiated form Server Console");
if(TextileBackup.restoreAwaitThread == null || !TextileBackup.restoreAwaitThread.isRunning()) { if(Statics.restoreAwaitThread == null || !Statics.restoreAwaitThread.isAlive()) {
TextileBackup.restoreAwaitThread = new AwaitThread( Statics.restoreAwaitThread = new AwaitThread(
TextileBackup.CONFIG.restoreDelay, Statics.CONFIG.restoreDelay,
RestoreHelper.create(dateTime, ctx.getSource().getMinecraftServer(), comment) RestoreHelper.create(dateTime, ctx.getSource().getMinecraftServer(), comment)
); );
TextileBackup.restoreAwaitThread.start(); Statics.restoreAwaitThread.start();
} else if(TextileBackup.restoreAwaitThread != null && TextileBackup.restoreAwaitThread.isRunning()) { } else if(Statics.restoreAwaitThread != null && Statics.restoreAwaitThread.isAlive()) {
ctx.getSource().sendFeedback(new LiteralText("Someone has already started another restoration."), false); ctx.getSource().sendFeedback(new LiteralText("Someone has already started another restoration."), false);
} }

View File

@ -0,0 +1,103 @@
package net.szum123321.textile_backup.core;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.text.LiteralText;
import net.minecraft.text.MutableText;
import net.minecraft.util.Formatting;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.MessageFactory;
import org.apache.logging.log4j.message.ParameterizedMessageFactory;
import org.apache.logging.log4j.spi.StandardLevel;
/*
This is practically just a copy-pate of Cotton's ModLogger with few changes
*/
public class CustomLogger {
private final boolean isDev = FabricLoader.getInstance().isDevelopmentEnvironment();
private final MessageFactory messageFactory;
private final Logger logger;
private final String prefix;
private final MutableText prefixText;
public CustomLogger(String name, String prefix) {
this.messageFactory = ParameterizedMessageFactory.INSTANCE;
this.logger = LogManager.getLogger(name, messageFactory);
this.prefix = "[" + prefix + "]" + " ";
this.prefixText = new LiteralText(prefix).formatted(Formatting.AQUA);
}
public void log(Level level, String msg, Object... data) {
logger.log(level, prefix + msg, data);
}
public void trace(String msg, Object... data) {
log(Level.TRACE, msg, data);
}
public void debug(String msg, Object... data) { log(Level.DEBUG, msg, data); }
public void info(String msg, Object... data) { log(Level.INFO, msg, data); }
public void warn(String msg, Object... data) {
log(Level.WARN, msg, data);
}
public void error(String msg, Object... data) {
log(Level.ERROR, msg, data);
}
public void fatal(String msg, Object... data) {
log(Level.FATAL, msg, data);
}
/*
public void warn(String msg, Throwable throwable) { logger.warn(prefix + msg, throwable); }
public void error(String msg, Throwable throwable) { logger.error(prefix + msg, throwable); }
public void fatal(String msg, Throwable throwable) { logger.fatal(prefix + msg, throwable); }
*/
public void devError(String msg, Object... data) {
if (isDev) error(msg, data);
}
public void devWarn(String msg, Object... data) {
if (isDev) warn(msg, data);
}
public void devInfo(String msg, Object... data) {
if (isDev) info(msg, data);
}
public void devDebug(String msg, Object... data) {
if (isDev) debug(msg, data);
}
public void devTrace(String msg, Object... data) {
if(isDev) trace(msg, data);
}
private void sendToPlayer(Level level, ServerCommandSource source, String msg, Object... args) {
if(source != null && source.getEntity() != null) {
LiteralText text = new LiteralText(messageFactory.newMessage(msg, args).getFormattedMessage());
if(level.intLevel() >= StandardLevel.WARN.intLevel())
text.formatted(Formatting.RED);
source.sendFeedback(prefixText.append(text), false);
}
}
public void sendInfo(ServerCommandSource source, String msg, Object... args) {
sendToPlayer(Level.INFO, source, msg, args);
info(msg, args);
}
public void sendError(ServerCommandSource source, String msg, Object... args) {
sendToPlayer(Level.ERROR, source, msg, args);
}
}

View File

@ -20,14 +20,11 @@ package net.szum123321.textile_backup.core;
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.text.LiteralText;
import net.minecraft.util.Formatting;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryKey; import net.minecraft.util.registry.RegistryKey;
import net.minecraft.world.dimension.DimensionType; import net.minecraft.world.dimension.DimensionType;
import net.szum123321.textile_backup.ConfigHandler; import net.szum123321.textile_backup.ConfigHandler;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.mixin.MinecraftServerSessionAccessor; import net.szum123321.textile_backup.mixin.MinecraftServerSessionAccessor;
import java.io.File; import java.io.File;
@ -50,12 +47,12 @@ public class Utilities {
public static boolean isBlacklisted(Path path) { public static boolean isBlacklisted(Path path) {
if(isWindows()) { //hotfix! if(isWindows()) { //hotfix!
if (path.getFileName().toString().equals("session.lock")) { if (path.getFileName().toString().equals("session.lock")) {
TextileBackup.LOGGER.trace("Skipping session.lock"); Statics.LOGGER.trace("Skipping session.lock");
return true; return true;
} }
} }
for(String i : TextileBackup.CONFIG.fileBlacklist) { for(String i : Statics.CONFIG.fileBlacklist) {
if(path.startsWith(i)) if(path.startsWith(i))
return true; return true;
} }
@ -90,22 +87,22 @@ public class Utilities {
} }
public static File getBackupRootPath(String worldName) { public static File getBackupRootPath(String worldName) {
File path = new File(TextileBackup.CONFIG.path).getAbsoluteFile(); File path = new File(Statics.CONFIG.path).getAbsoluteFile();
if (TextileBackup.CONFIG.perWorldBackup) if (Statics.CONFIG.perWorldBackup)
path = path.toPath().resolve(worldName).toFile(); path = path.toPath().resolve(worldName).toFile();
if (!path.exists()) { if (!path.exists()) {
try { try {
path.mkdirs(); path.mkdirs();
} catch (Exception e) { } catch (Exception e) {
TextileBackup.LOGGER.error("An exception occurred!", e); Statics.LOGGER.error("An exception occurred!", e);
return FabricLoader return FabricLoader
.getInstance() .getInstance()
.getGameDirectory() .getGameDirectory()
.toPath() .toPath()
.resolve(TextileBackup.CONFIG.path) .resolve(Statics.CONFIG.path)
.toFile(); .toFile();
} }
} }
@ -155,8 +152,8 @@ public class Utilities {
} }
public static DateTimeFormatter getDateTimeFormatter(){ public static DateTimeFormatter getDateTimeFormatter(){
if(!TextileBackup.CONFIG.dateTimeFormat.equals("")) if(!Statics.CONFIG.dateTimeFormat.equals(""))
return DateTimeFormatter.ofPattern(TextileBackup.CONFIG.dateTimeFormat); return DateTimeFormatter.ofPattern(Statics.CONFIG.dateTimeFormat);
else else
return getBackupDateTimeFormatter(); return getBackupDateTimeFormatter();
} }
@ -178,16 +175,4 @@ public class Utilities {
return LocalTime.ofNanoOfDay(duration.toNanos()).format(formatter); return LocalTime.ofNanoOfDay(duration.toNanos()).format(formatter);
} }
public static void info(String s, ServerCommandSource ctx){
if(ctx != null && ctx.getEntity() != null)
ctx.sendFeedback(new LiteralText(s), false);
TextileBackup.LOGGER.info(s);
}
public static void sendError(String message, ServerCommandSource source) {
if(source != null) {
source.sendFeedback(new LiteralText(message).styled(style -> style.withColor(Formatting.RED)), false);
}
}
} }

View File

@ -19,7 +19,7 @@
package net.szum123321.textile_backup.core.create; package net.szum123321.textile_backup.core.create;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.Utilities; import net.szum123321.textile_backup.core.Utilities;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
@ -48,10 +48,10 @@ public class BackupHelper {
builder.append(" on: "); builder.append(" on: ");
builder.append(Utilities.getDateTimeFormatter().format(LocalDateTime.now())); builder.append(Utilities.getDateTimeFormatter().format(LocalDateTime.now()));
Utilities.info(builder.toString(), null); Statics.LOGGER.info(builder.toString());
if (ctx.shouldSave()) { if (ctx.shouldSave()) {
Utilities.info("Saving server...", ctx.getCommandSource()); Statics.LOGGER.sendInfo(ctx.getCommandSource(), "Saving server...");
ctx.getServer().save(true, true, false); ctx.getServer().save(true, true, false);
} }
@ -63,24 +63,24 @@ public class BackupHelper {
AtomicInteger deletedFiles = new AtomicInteger(); AtomicInteger deletedFiles = new AtomicInteger();
if (root.isDirectory() && root.exists() && root.listFiles() != null) { if (root.isDirectory() && root.exists() && root.listFiles() != null) {
if (TextileBackup.CONFIG.maxAge > 0) { // delete files older that configured if (Statics.CONFIG.maxAge > 0) { // delete files older that configured
final LocalDateTime now = LocalDateTime.now(); final LocalDateTime now = LocalDateTime.now();
Arrays.stream(root.listFiles()) Arrays.stream(root.listFiles())
.filter(BackupHelper::isFileOk) .filter(BackupHelper::isFileOk)
.filter(f -> Utilities.getFileCreationTime(f).isPresent()) // We check if we can get file's creation date so that the next line won't throw an exception .filter(f -> Utilities.getFileCreationTime(f).isPresent()) // We check if we can get file's creation date so that the next line won't throw an exception
.filter(f -> now.toEpochSecond(ZoneOffset.UTC) - Utilities.getFileCreationTime(f).get().toEpochSecond(ZoneOffset.UTC) > TextileBackup.CONFIG.maxAge) .filter(f -> now.toEpochSecond(ZoneOffset.UTC) - Utilities.getFileCreationTime(f).get().toEpochSecond(ZoneOffset.UTC) > Statics.CONFIG.maxAge)
.forEach(f -> { .forEach(f -> {
if(f.delete()) { if(f.delete()) {
Utilities.info("Deleting: " + f.getName(), ctx); Statics.LOGGER.sendInfo(ctx, "Deleting: {}", f.getName());
deletedFiles.getAndIncrement(); deletedFiles.getAndIncrement();
} else { } else {
Utilities.sendError("Something went wrong while deleting: " + f.getName(), ctx); Statics.LOGGER.sendError(ctx, "Something went wrong while deleting: {}.", f.getName());
} }
}); });
} }
if (TextileBackup.CONFIG.backupsToKeep > 0 && root.listFiles().length > TextileBackup.CONFIG.backupsToKeep) { if (Statics.CONFIG.backupsToKeep > 0 && root.listFiles().length > Statics.CONFIG.backupsToKeep) {
int i = root.listFiles().length; int i = root.listFiles().length;
Iterator<File> it = Arrays.stream(root.listFiles()) Iterator<File> it = Arrays.stream(root.listFiles())
@ -89,35 +89,35 @@ public class BackupHelper {
.sorted(Comparator.comparing(f -> Utilities.getFileCreationTime(f).get())) .sorted(Comparator.comparing(f -> Utilities.getFileCreationTime(f).get()))
.iterator(); .iterator();
while(i > TextileBackup.CONFIG.backupsToKeep && it.hasNext()) { while(i > Statics.CONFIG.backupsToKeep && it.hasNext()) {
File f = it.next(); File f = it.next();
if(f.delete()) { if(f.delete()) {
Utilities.info("Deleting: " + f.getName(), ctx); Statics.LOGGER.sendInfo(ctx, "Deleting: {}", f.getName());
deletedFiles.getAndIncrement(); deletedFiles.getAndIncrement();
} else { } else {
Utilities.sendError("Something went wrong while deleting: " + f.getName(), ctx); Statics.LOGGER.sendError(ctx, "Something went wrong while deleting: {}.", f.getName());
} }
i--; i--;
} }
} }
if (TextileBackup.CONFIG.maxSize > 0 && FileUtils.sizeOfDirectory(root) / 1024 > TextileBackup.CONFIG.maxSize) { if (Statics.CONFIG.maxSize > 0 && FileUtils.sizeOfDirectory(root) / 1024 > Statics.CONFIG.maxSize) {
Iterator<File> it = Arrays.stream(root.listFiles()) Iterator<File> it = Arrays.stream(root.listFiles())
.filter(BackupHelper::isFileOk) .filter(BackupHelper::isFileOk)
.filter(f -> Utilities.getFileCreationTime(f).isPresent()) .filter(f -> Utilities.getFileCreationTime(f).isPresent())
.sorted(Comparator.comparing(f -> Utilities.getFileCreationTime(f).get())) .sorted(Comparator.comparing(f -> Utilities.getFileCreationTime(f).get()))
.iterator(); .iterator();
while(FileUtils.sizeOfDirectory(root) / 1024 > TextileBackup.CONFIG.maxSize && it.hasNext()) { while(FileUtils.sizeOfDirectory(root) / 1024 > Statics.CONFIG.maxSize && it.hasNext()) {
File f = it.next(); File f = it.next();
if(f.delete()) { if(f.delete()) {
Utilities.info("Deleting: " + f.getName(), ctx); Statics.LOGGER.sendInfo(ctx, "Deleting: {}", f.getName());
deletedFiles.getAndIncrement(); deletedFiles.getAndIncrement();
} else { } else {
Utilities.sendError("Something went wrong while deleting: " + f.getName(), ctx); Statics.LOGGER.sendError(ctx, "Something went wrong while deleting: {}.", f.getName());
} }
} }
} }

View File

@ -1,7 +1,7 @@
package net.szum123321.textile_backup.core.create; package net.szum123321.textile_backup.core.create;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import java.time.Instant; import java.time.Instant;
@ -17,10 +17,10 @@ public class BackupScheduler {
public void tick(MinecraftServer server) { public void tick(MinecraftServer server) {
long now = Instant.now().getEpochSecond(); long now = Instant.now().getEpochSecond();
if(TextileBackup.CONFIG.doBackupsOnEmptyServer || server.getPlayerManager().getCurrentPlayerCount() > 0) { if(Statics.CONFIG.doBackupsOnEmptyServer || server.getPlayerManager().getCurrentPlayerCount() > 0) {
if(scheduled) { if(scheduled) {
if(nextBackup <= now) { if(nextBackup <= now) {
TextileBackup.executorService.submit( Statics.executorService.submit(
BackupHelper.create( BackupHelper.create(
new BackupContext.Builder() new BackupContext.Builder()
.setServer(server) .setServer(server)
@ -30,15 +30,15 @@ public class BackupScheduler {
) )
); );
nextBackup = now + TextileBackup.CONFIG.backupInterval; nextBackup = now + Statics.CONFIG.backupInterval;
} }
} else { } else {
nextBackup = now + TextileBackup.CONFIG.backupInterval; nextBackup = now + Statics.CONFIG.backupInterval;
scheduled = true; scheduled = true;
} }
} else if(!TextileBackup.CONFIG.doBackupsOnEmptyServer && server.getPlayerManager().getCurrentPlayerCount() == 0) { } else if(!Statics.CONFIG.doBackupsOnEmptyServer && server.getPlayerManager().getCurrentPlayerCount() == 0) {
if(scheduled && nextBackup <= now) { if(scheduled && nextBackup <= now) {
TextileBackup.executorService.submit( Statics.executorService.submit(
BackupHelper.create( BackupHelper.create(
new BackupContext.Builder() new BackupContext.Builder()
.setServer(server) .setServer(server)

View File

@ -20,7 +20,7 @@ package net.szum123321.textile_backup.core.create;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.create.compressors.LZMACompressor; import net.szum123321.textile_backup.core.create.compressors.LZMACompressor;
import net.szum123321.textile_backup.core.create.compressors.ParallelBZip2Compressor; import net.szum123321.textile_backup.core.create.compressors.ParallelBZip2Compressor;
import net.szum123321.textile_backup.core.create.compressors.ParallelGzipCompressor; import net.szum123321.textile_backup.core.create.compressors.ParallelGzipCompressor;
@ -44,11 +44,11 @@ public class MakeBackupRunnable implements Runnable {
@Override @Override
public void run() { public void run() {
Utilities.info("Starting backup", commandSource); Statics.LOGGER.sendInfo(commandSource, "Starting backup");
File world = Utilities.getWorldFolder(server); File world = Utilities.getWorldFolder(server);
TextileBackup.LOGGER.trace("Minecraft world is: {}", world); Statics.LOGGER.trace("Minecraft world is: {}", world);
File outFile = Utilities File outFile = Utilities
.getBackupRootPath(Utilities.getLevelName(server)) .getBackupRootPath(Utilities.getLevelName(server))
@ -56,31 +56,30 @@ public class MakeBackupRunnable implements Runnable {
.resolve(getFileName()) .resolve(getFileName())
.toFile(); .toFile();
TextileBackup.LOGGER.trace("Outfile is: {}", outFile); Statics.LOGGER.trace("Outfile is: {}", outFile);
outFile.getParentFile().mkdirs(); outFile.getParentFile().mkdirs();
try { try {
outFile.createNewFile(); outFile.createNewFile();
} catch (IOException e) { } catch (IOException e) {
TextileBackup.LOGGER.error("An exception occurred when trying to create new backup file!", e); Statics.LOGGER.error("An exception occurred when trying to create new backup file!", e);
Statics.LOGGER.sendError(commandSource, "An exception occurred when trying to create new backup file!");
Utilities.sendError("An exception occurred when trying to create new backup file!", commandSource);
return; return;
} }
int coreCount; int coreCount;
if(TextileBackup.CONFIG.compressionCoreCountLimit <= 0) { if(Statics.CONFIG.compressionCoreCountLimit <= 0) {
coreCount = Runtime.getRuntime().availableProcessors(); coreCount = Runtime.getRuntime().availableProcessors();
} else { } else {
coreCount = Math.min(TextileBackup.CONFIG.compressionCoreCountLimit, Runtime.getRuntime().availableProcessors()); coreCount = Math.min(Statics.CONFIG.compressionCoreCountLimit, Runtime.getRuntime().availableProcessors());
} }
TextileBackup.LOGGER.trace("Running compression on {} threads. Available cores = {}", coreCount, Runtime.getRuntime().availableProcessors()); Statics.LOGGER.trace("Running compression on {} threads. Available cores = {}", coreCount, Runtime.getRuntime().availableProcessors());
switch (TextileBackup.CONFIG.format) { switch (Statics.CONFIG.format) {
case ZIP: case ZIP:
ParallelZipCompressor.createArchive(world, outFile, commandSource, coreCount); ParallelZipCompressor.createArchive(world, outFile, commandSource, coreCount);
break; break;
@ -98,8 +97,8 @@ public class MakeBackupRunnable implements Runnable {
break; break;
default: default:
TextileBackup.LOGGER.warn("Specified compressor ({}) is not supported! Zip will be used instead!", TextileBackup.CONFIG.format); Statics.LOGGER.warn("Specified compressor ({}) is not supported! Zip will be used instead!", Statics.CONFIG.format);
Utilities.sendError("Error! No correct compression format specified! Using default compressor!", commandSource); Statics.LOGGER.sendError(commandSource, "Error! No correct compression format specified! Using default compressor!");
ParallelZipCompressor.createArchive(world, outFile, commandSource, coreCount); ParallelZipCompressor.createArchive(world, outFile, commandSource, coreCount);
break; break;
@ -107,12 +106,12 @@ public class MakeBackupRunnable implements Runnable {
BackupHelper.executeFileLimit(commandSource, Utilities.getLevelName(server)); BackupHelper.executeFileLimit(commandSource, Utilities.getLevelName(server));
Utilities.info("Done!", commandSource); Statics.LOGGER.sendInfo(commandSource, "Done!");
} }
private String getFileName(){ private String getFileName(){
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
return Utilities.getDateTimeFormatter().format(now) + (comment != null ? "#" + comment.replace("#", "") : "") + TextileBackup.CONFIG.format.getString(); return Utilities.getDateTimeFormatter().format(now) + (comment != null ? "#" + comment.replace("#", "") : "") + Statics.CONFIG.format.getString();
} }
} }

View File

@ -1,7 +1,7 @@
package net.szum123321.textile_backup.core.create.compressors; package net.szum123321.textile_backup.core.create.compressors;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.Utilities; import net.szum123321.textile_backup.core.Utilities;
import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
@ -16,7 +16,7 @@ import java.time.Instant;
public class LZMACompressor { public class LZMACompressor {
public static void createArchive(File in, File out, ServerCommandSource ctx) { public static void createArchive(File in, File out, ServerCommandSource ctx) {
Utilities.info("Starting compression...", ctx); Statics.LOGGER.sendInfo(ctx, "Starting compression...");
Instant start = Instant.now(); Instant start = Instant.now();
@ -46,17 +46,17 @@ public class LZMACompressor {
arc.closeArchiveEntry(); arc.closeArchiveEntry();
} catch (IOException e) { } catch (IOException e) {
TextileBackup.LOGGER.error("An exception occurred while trying to compress: " + path.getFileName(), e); Statics.LOGGER.error("An exception occurred while trying to compress: {}", path.getFileName(), e);
Utilities.sendError("Something went wrong while compressing files!", ctx); Statics.LOGGER.sendError(ctx, "Something went wrong while compressing files!");
} }
}); });
arc.finish(); arc.finish();
} catch (IOException e) { } catch (IOException e) {
TextileBackup.LOGGER.error("An exception occurred!", e); Statics.LOGGER.error("An exception occurred!", e);
Utilities.sendError("Something went wrong while compressing files!", ctx); Statics.LOGGER.sendError(ctx, "Something went wrong while compressing files!");
} }
Utilities.info("Compression took: " + Utilities.formatDuration(Duration.between(start, Instant.now())) + " seconds.", ctx); Statics.LOGGER.sendInfo(ctx, "Compression took: {} seconds.", Utilities.formatDuration(Duration.between(start, Instant.now())));
} }
} }

View File

@ -1,7 +1,7 @@
package net.szum123321.textile_backup.core.create.compressors; package net.szum123321.textile_backup.core.create.compressors;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.Utilities; import net.szum123321.textile_backup.core.Utilities;
import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
@ -16,7 +16,7 @@ import java.time.Instant;
public class ParallelBZip2Compressor { public class ParallelBZip2Compressor {
public static void createArchive(File in, File out, ServerCommandSource ctx, int coreLimit) { public static void createArchive(File in, File out, ServerCommandSource ctx, int coreLimit) {
Utilities.info("Starting compression...", ctx); Statics.LOGGER.sendInfo(ctx, "Starting compression...");
BZip2OutputStreamSettings settings = new BZip2OutputStreamSettings().setNumberOfEncoderThreads(coreLimit); BZip2OutputStreamSettings settings = new BZip2OutputStreamSettings().setNumberOfEncoderThreads(coreLimit);
@ -48,17 +48,17 @@ public class ParallelBZip2Compressor {
arc.closeArchiveEntry(); arc.closeArchiveEntry();
} catch (IOException e) { } catch (IOException e) {
TextileBackup.LOGGER.error("An exception occurred while trying to compress: " + path.getFileName(), e); Statics.LOGGER.error("An exception occurred while trying to compress: {}", path.getFileName(), e);
Utilities.sendError("Something went wrong while compressing files!", ctx); Statics.LOGGER.sendError(ctx, "Something went wrong while compressing files!");
} }
}); });
arc.finish(); arc.finish();
} catch (IOException e) { } catch (IOException e) {
TextileBackup.LOGGER.error("An exception occurred!", e); Statics.LOGGER.error("An exception occurred!", e);
Utilities.sendError("Something went wrong while compressing files!", ctx); Statics.LOGGER.sendError(ctx, "Something went wrong while compressing files!");
} }
Utilities.info("Compression took: " + Utilities.formatDuration(Duration.between(start, Instant.now())) + " seconds.", ctx); Statics.LOGGER.sendInfo(ctx, "Compression took: {} seconds.", Utilities.formatDuration(Duration.between(start, Instant.now())));
} }
} }

View File

@ -1,7 +1,7 @@
package net.szum123321.textile_backup.core.create.compressors; package net.szum123321.textile_backup.core.create.compressors;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.Utilities; import net.szum123321.textile_backup.core.Utilities;
import org.anarres.parallelgzip.ParallelGZIPOutputStream; import org.anarres.parallelgzip.ParallelGZIPOutputStream;
import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveEntry;
@ -15,7 +15,7 @@ import java.time.Instant;
public class ParallelGzipCompressor { public class ParallelGzipCompressor {
public static void createArchive(File in, File out, ServerCommandSource ctx, int coreLimit) { public static void createArchive(File in, File out, ServerCommandSource ctx, int coreLimit) {
Utilities.info("Starting compression...", ctx); Statics.LOGGER.sendInfo(ctx, "Starting compression...");
Instant start = Instant.now(); Instant start = Instant.now();
@ -45,17 +45,17 @@ public class ParallelGzipCompressor {
arc.closeArchiveEntry(); arc.closeArchiveEntry();
} catch (IOException e) { } catch (IOException e) {
TextileBackup.LOGGER.error("An exception occurred while trying to compress file: " + path, e); Statics.LOGGER.error("An exception occurred while trying to compress: {}", path.getFileName(), e);
Utilities.sendError("Something went wrong while compressing files!", ctx); Statics.LOGGER.sendError(ctx, "Something went wrong while compressing files!");
} }
}); });
arc.finish(); arc.finish();
} catch (IOException e) { } catch (IOException e) {
TextileBackup.LOGGER.error("An exception happened!", e); Statics.LOGGER.error("An exception occurred!", e);
Utilities.sendError("Something went wrong while compressing files!", ctx); Statics.LOGGER.sendError(ctx, "Something went wrong while compressing files!");
} }
Utilities.info("Compression took: " + Utilities.formatDuration(Duration.between(start, Instant.now())) + " seconds.", ctx); Statics.LOGGER.sendInfo(ctx, "Compression took: {} seconds.", Utilities.formatDuration(Duration.between(start, Instant.now())));
} }
} }

View File

@ -1,7 +1,7 @@
package net.szum123321.textile_backup.core.create.compressors; package net.szum123321.textile_backup.core.create.compressors;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.Utilities; import net.szum123321.textile_backup.core.Utilities;
import org.apache.commons.compress.archivers.zip.*; import org.apache.commons.compress.archivers.zip.*;
import org.apache.commons.compress.parallel.InputStreamSupplier; import org.apache.commons.compress.parallel.InputStreamSupplier;
@ -24,7 +24,7 @@ import java.util.zip.ZipEntry;
public class ParallelZipCompressor { public class ParallelZipCompressor {
public static void createArchive(File in, File out, ServerCommandSource ctx, int coreLimit) { public static void createArchive(File in, File out, ServerCommandSource ctx, int coreLimit) {
Utilities.info("Starting compression...", ctx); Statics.LOGGER.sendInfo(ctx, "Starting compression...");
Instant start = Instant.now(); Instant start = Instant.now();
@ -36,7 +36,7 @@ public class ParallelZipCompressor {
arc.setMethod(ZipArchiveOutputStream.DEFLATED); arc.setMethod(ZipArchiveOutputStream.DEFLATED);
arc.setUseZip64(Zip64Mode.AsNeeded); arc.setUseZip64(Zip64Mode.AsNeeded);
arc.setLevel(TextileBackup.CONFIG.compression); arc.setLevel(Statics.CONFIG.compression);
arc.setComment("Created on: " + Utilities.getDateTimeFormatter().format(LocalDateTime.now())); arc.setComment("Created on: " + Utilities.getDateTimeFormatter().format(LocalDateTime.now()));
File input = in.getCanonicalFile(); File input = in.getCanonicalFile();
@ -56,11 +56,11 @@ public class ParallelZipCompressor {
arc.finish(); arc.finish();
} catch (IOException | InterruptedException | ExecutionException e) { } catch (IOException | InterruptedException | ExecutionException e) {
TextileBackup.LOGGER.error("An exception occured!", e); Statics.LOGGER.error("An exception occurred!", e);
Utilities.sendError("Something went wrong while compressing files!", ctx); Statics.LOGGER.sendError(ctx, "Something went wrong while compressing files!");
} }
Utilities.info("Compression took: " + Utilities.formatDuration(Duration.between(start, Instant.now())) + " seconds.", ctx); Statics.LOGGER.sendInfo(ctx, "Compression took: {} seconds.", Utilities.formatDuration(Duration.between(start, Instant.now())));
} }
static class FileInputStreamSupplier implements InputStreamSupplier { static class FileInputStreamSupplier implements InputStreamSupplier {
@ -75,7 +75,7 @@ public class ParallelZipCompressor {
try { try {
stream = Files.newInputStream(sourceFile); stream = Files.newInputStream(sourceFile);
} catch (IOException e) { } catch (IOException e) {
TextileBackup.LOGGER.error("An exception occurred while trying to create input stream!", e); Statics.LOGGER.error("An exception occurred while trying to create input stream!", e);
} }
return stream; return stream;

View File

@ -1,11 +1,10 @@
package net.szum123321.textile_backup.core.restore; package net.szum123321.textile_backup.core.restore;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
public class AwaitThread extends Thread { public class AwaitThread extends Thread {
private final int delay; private final int delay;
private final Runnable taskRunnable; private final Runnable taskRunnable;
private boolean running;
public AwaitThread(int delay, Runnable taskRunnable) { public AwaitThread(int delay, Runnable taskRunnable) {
this.delay = delay; this.delay = delay;
@ -14,22 +13,13 @@ public class AwaitThread extends Thread {
@Override @Override
public void run() { public void run() {
TextileBackup.LOGGER.info("Countdown begins..."); Statics.LOGGER.info("Countdown begins...");
running = true; // 𝄞 This is final count down! Tu ruru Tu, Tu Ru Tu Tu ♪
int counter = delay * 10; // done to increase responsiveness try {
Thread.sleep(delay * 1000);
} catch (InterruptedException e) {
while(counter > 0) { // 𝄞 This is final count down! Tu ruru Tu, Tu Ru Tu Tu ♪ return;
try {
Thread.sleep(100);
counter--;
} catch (InterruptedException e) {
TextileBackup.LOGGER.info("An exception occurred while counting down", e);
}
if(!running)
return;
} }
/* /*
@ -38,15 +28,5 @@ public class AwaitThread extends Thread {
And maybe we'll come back And maybe we'll come back
*/ */
new Thread(taskRunnable).start(); new Thread(taskRunnable).start();
running = false;
}
public synchronized void kill() {
this.running = false;
}
public boolean isRunning() {
return running;
} }
} }

View File

@ -20,7 +20,7 @@ package net.szum123321.textile_backup.core.restore;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.szum123321.textile_backup.core.LivingServer; import net.szum123321.textile_backup.core.LivingServer;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.Utilities; import net.szum123321.textile_backup.core.Utilities;
import net.szum123321.textile_backup.core.create.BackupContext; import net.szum123321.textile_backup.core.create.BackupContext;
import net.szum123321.textile_backup.core.create.BackupHelper; import net.szum123321.textile_backup.core.create.BackupHelper;
@ -48,11 +48,11 @@ public class RestoreBackupRunnable implements Runnable {
@Override @Override
public void run() { public void run() {
TextileBackup.LOGGER.info("Shutting down server..."); Statics.LOGGER.info("Shutting down server...");
server.stop(false); server.stop(false);
awaitServerShutdown(); awaitServerShutdown();
if(TextileBackup.CONFIG.backupOldWorlds) { if(Statics.CONFIG.backupOldWorlds) {
BackupHelper.create( BackupHelper.create(
new BackupContext.Builder() new BackupContext.Builder()
.setServer(server) .setServer(server)
@ -64,14 +64,14 @@ public class RestoreBackupRunnable implements Runnable {
File worldFile = Utilities.getWorldFolder(server); File worldFile = Utilities.getWorldFolder(server);
TextileBackup.LOGGER.info("Deleting old world..."); Statics.LOGGER.info("Deleting old world...");
if(!deleteDirectory(worldFile)) if(!deleteDirectory(worldFile))
TextileBackup.LOGGER.error("Something went wrong while deleting old world!"); Statics.LOGGER.error("Something went wrong while deleting old world!");
worldFile.mkdirs(); worldFile.mkdirs();
try(FileInputStream fileInputStream = new FileInputStream(backupFile)) { try(FileInputStream fileInputStream = new FileInputStream(backupFile)) {
TextileBackup.LOGGER.info("Starting decompression..."); Statics.LOGGER.info("Starting decompression...");
switch(Utilities.getFileExtension(backupFile).orElseThrow(() -> new NoSuchElementException("Couldn't get file extention!"))) { switch(Utilities.getFileExtension(backupFile).orElseThrow(() -> new NoSuchElementException("Couldn't get file extention!"))) {
case ZIP: case ZIP:
@ -91,10 +91,10 @@ public class RestoreBackupRunnable implements Runnable {
break; break;
} }
} catch (IOException e) { } catch (IOException e) {
TextileBackup.LOGGER.error("Exception occurred!", e); Statics.LOGGER.error("Exception occurred!", e);
} }
TextileBackup.LOGGER.info("Done."); Statics.LOGGER.info("Done.");
} }
private void awaitServerShutdown() { private void awaitServerShutdown() {
@ -102,7 +102,7 @@ public class RestoreBackupRunnable implements Runnable {
try { try {
Thread.sleep(1000); Thread.sleep(1000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
TextileBackup.LOGGER.error("Exception occurred!", e); Statics.LOGGER.error("Exception occurred!", e);
} }
} }
} }

View File

@ -20,7 +20,7 @@ package net.szum123321.textile_backup.core.restore;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.text.LiteralText; import net.minecraft.text.LiteralText;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.Utilities; import net.szum123321.textile_backup.core.Utilities;
import java.io.File; import java.io.File;
@ -40,9 +40,9 @@ public class RestoreHelper {
.orElseThrow(() -> new NoSuchElementException("Couldn't find given backup file!")); .orElseThrow(() -> new NoSuchElementException("Couldn't find given backup file!"));
server.getPlayerManager().getPlayerList() server.getPlayerManager().getPlayerList()
.forEach(serverPlayerEntity -> serverPlayerEntity.sendMessage(new LiteralText("Warning! The server is going to shut down in " + TextileBackup.CONFIG.restoreDelay + " seconds!"), false)); .forEach(serverPlayerEntity -> serverPlayerEntity.sendMessage(new LiteralText("Warning! The server is going to shut down in " + Statics.CONFIG.restoreDelay + " seconds!"), false));
TextileBackup.globalShutdownBackupFlag.set(false); Statics.globalShutdownBackupFlag.set(false);
return new Thread(new RestoreBackupRunnable(server, backupFile, comment)); return new Thread(new RestoreBackupRunnable(server, backupFile, comment));
} }

View File

@ -18,7 +18,7 @@
package net.szum123321.textile_backup.core.restore.decompressors; package net.szum123321.textile_backup.core.restore.decompressors;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.Utilities; import net.szum123321.textile_backup.core.Utilities;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
@ -42,7 +42,7 @@ public class GenericTarDecompressor {
while ((entry = archiveInputStream.getNextTarEntry()) != null) { while ((entry = archiveInputStream.getNextTarEntry()) != null) {
if(!archiveInputStream.canReadEntryData(entry)) { if(!archiveInputStream.canReadEntryData(entry)) {
TextileBackup.LOGGER.warn("Something when wrong while trying to decompress {}", entry.getName()); Statics.LOGGER.warn("Something when wrong while trying to decompress {}", entry.getName());
continue; continue;
} }
@ -60,14 +60,14 @@ public class GenericTarDecompressor {
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) { BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {
IOUtils.copy(archiveInputStream, bufferedOutputStream); IOUtils.copy(archiveInputStream, bufferedOutputStream);
} catch (IOException e) { } catch (IOException e) {
TextileBackup.LOGGER.error("An exception occurred while trying to decompress file: " + file.getName(), e); Statics.LOGGER.error("An exception occurred while trying to decompress file: {}", file.getName(), e);
} }
} }
} }
} catch (IOException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { } catch (IOException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
TextileBackup.LOGGER.error("An exception occurred! ", e); Statics.LOGGER.error("An exception occurred! ", e);
} }
TextileBackup.LOGGER.info("Decompression took {} seconds.", Utilities.formatDuration(Duration.between(start, Instant.now()))); Statics.LOGGER.info("Decompression took {} seconds.", Utilities.formatDuration(Duration.between(start, Instant.now())));
} }
} }

View File

@ -18,7 +18,7 @@
package net.szum123321.textile_backup.core.restore.decompressors; package net.szum123321.textile_backup.core.restore.decompressors;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.Utilities; import net.szum123321.textile_backup.core.Utilities;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
@ -39,7 +39,7 @@ public class ZipDecompressor {
while ((entry = zipInputStream.getNextZipEntry()) != null) { while ((entry = zipInputStream.getNextZipEntry()) != null) {
if(!zipInputStream.canReadEntryData(entry)){ if(!zipInputStream.canReadEntryData(entry)){
TextileBackup.LOGGER.warn("Something when wrong while trying to decompress {}", entry.getName()); Statics.LOGGER.warn("Something when wrong while trying to decompress {}", entry.getName());
continue; continue;
} }
@ -57,14 +57,14 @@ public class ZipDecompressor {
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) { BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {
IOUtils.copy(zipInputStream, bufferedOutputStream); IOUtils.copy(zipInputStream, bufferedOutputStream);
} catch (IOException e) { } catch (IOException e) {
TextileBackup.LOGGER.error("An exception occurred while trying to decompress file: " + file.getName(), e); Statics.LOGGER.error("An exception occurred while trying to decompress file: {}", file.getName(), e);
} }
} }
} }
} catch (IOException e) { } catch (IOException e) {
TextileBackup.LOGGER.error("An exception occurred! ", e); Statics.LOGGER.error("An exception occurred! ", e);
} }
TextileBackup.LOGGER.info("Compression took: {} seconds.", Utilities.formatDuration(Duration.between(start, Instant.now()))); Statics.LOGGER.info("Compression took: {} seconds.", Utilities.formatDuration(Duration.between(start, Instant.now())));
} }
} }

View File

@ -20,7 +20,7 @@ package net.szum123321.textile_backup.mixin;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.szum123321.textile_backup.core.LivingServer; import net.szum123321.textile_backup.core.LivingServer;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.Statics;
import net.szum123321.textile_backup.core.create.BackupContext; import net.szum123321.textile_backup.core.create.BackupContext;
import net.szum123321.textile_backup.core.create.BackupHelper; import net.szum123321.textile_backup.core.create.BackupHelper;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
@ -34,8 +34,8 @@ public class MinecraftServerMixin implements LivingServer {
@Inject(method = "shutdown", at = @At(value = "INVOKE_ASSIGN", target = "Lnet/minecraft/server/MinecraftServer;save(ZZZ)Z")) @Inject(method = "shutdown", at = @At(value = "INVOKE_ASSIGN", target = "Lnet/minecraft/server/MinecraftServer;save(ZZZ)Z"))
public void onFinalWorldSave(CallbackInfo ci) { public void onFinalWorldSave(CallbackInfo ci) {
if (TextileBackup.CONFIG.shutdownBackup && TextileBackup.globalShutdownBackupFlag.get()) { if (Statics.CONFIG.shutdownBackup && Statics.globalShutdownBackupFlag.get()) {
TextileBackup.executorService.submit( Statics.executorService.submit(
BackupHelper.create( BackupHelper.create(
new BackupContext.Builder() new BackupContext.Builder()
.setServer((MinecraftServer) (Object) this) .setServer((MinecraftServer) (Object) this)