Refactor backup command.

This commit is contained in:
Logan Gorence 2021-12-20 23:28:00 +00:00
parent 10f6bf98dd
commit 9413211a82
No known key found for this signature in database
GPG Key ID: 9743CEF10935949A

View File

@ -9,7 +9,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.ZipEntry;
@ -69,12 +68,30 @@ public class BackupCommand implements CommandExecutor {
final var backupFile = backupPath.resolve(
String.format("backup-%s.zip", Instant.now().toString())).toFile();
final var zipFileStream = new FileOutputStream(backupFile);
final var zipStream = new ZipOutputStream(new BufferedOutputStream(zipFileStream));
try (zipFileStream; var zipStream = new ZipOutputStream(
new BufferedOutputStream(zipFileStream))) {
try (zipFileStream; zipStream) {
backupPlugins(server, zipStream);
backupWorlds(server, zipStream);
} finally {
RUNNING.set(false);
server.sendMessage(Util.formatSystemMessage("Backup finished."));
}
}
private void backupPlugins(Server server, ZipOutputStream zipStream) {
try {
addDirectoryToZip(zipStream, server.getPluginsFolder().toPath());
} catch (IOException e) {
// TODO: Add error handling.
e.printStackTrace();
}
}
private void backupWorlds(Server server, ZipOutputStream zipStream) {
final var worlds = server.getWorlds();
for (World world : worlds) {
final var worldPath = world.getWorldFolder().toPath().toString();
final var worldPath = world.getWorldFolder().toPath();
// Save the world.
world.save();
@ -83,7 +100,19 @@ public class BackupCommand implements CommandExecutor {
world.setAutoSave(false);
try {
final var paths = Files.walk(Paths.get(worldPath))
addDirectoryToZip(zipStream, worldPath);
} catch (IOException e) {
// TODO: Add error handling.
e.printStackTrace();
}
// Re-enable auto saving for this world.
world.setAutoSave(true);
}
}
private void addDirectoryToZip(ZipOutputStream zipStream, Path directoryPath) throws IOException {
final var paths = Files.walk(directoryPath)
.filter(Files::isRegularFile)
.toList();
@ -98,16 +127,5 @@ public class BackupCommand implements CommandExecutor {
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Re-enable auto saving for this world.
world.setAutoSave(true);
}
} finally {
RUNNING.set(false);
server.sendMessage(Util.formatSystemMessage("Backup finished."));
}
}
}