Skip to content

Commit

Permalink
Merge pull request #404 from AzureAaron/nio-refactor
Browse files Browse the repository at this point in the history
NIO Refactor
  • Loading branch information
Aaron committed Nov 4, 2023
2 parents a309de2 + 0d738a4 commit d8bd4d6
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 20 deletions.
9 changes: 5 additions & 4 deletions src/main/java/de/hysky/skyblocker/skyblock/FairySouls.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -70,7 +72,7 @@ private static void loadFairySouls() {
NEURepoManager.NEU_REPO.getConstants().getFairySouls().getSoulLocations().forEach((location, fairySoulsForLocation) -> fairySouls.put(location, fairySoulsForLocation.stream().map(coordinate -> new BlockPos(coordinate.getX(), coordinate.getY(), coordinate.getZ())).collect(Collectors.toUnmodifiableSet())));
LOGGER.debug("[Skyblocker] Loaded {} fairy souls across {} locations", fairySouls.values().stream().mapToInt(Set::size).sum(), fairySouls.size());

try (BufferedReader reader = new BufferedReader(new FileReader(SkyblockerMod.CONFIG_DIR.resolve("found_fairy_souls.json").toFile()))) {
try (BufferedReader reader = Files.newBufferedReader(SkyblockerMod.CONFIG_DIR.resolve("found_fairy_souls.json"))) {
for (Map.Entry<String, JsonElement> foundFairiesForProfileJson : JsonParser.parseReader(reader).getAsJsonObject().asMap().entrySet()) {
Map<String, Set<BlockPos>> foundFairiesForProfile = new HashMap<>();
for (Map.Entry<String, JsonElement> foundFairiesForLocationJson : foundFairiesForProfileJson.getValue().getAsJsonObject().asMap().entrySet()) {
Expand All @@ -83,7 +85,7 @@ private static void loadFairySouls() {
foundFairies.put(foundFairiesForProfileJson.getKey(), foundFairiesForProfile);
}
LOGGER.debug("[Skyblocker] Loaded found fairy souls");
} catch (FileNotFoundException ignored) {
} catch (NoSuchFileException ignored) {
} catch (IOException e) {
LOGGER.error("[Skyblocker] Failed to load found fairy souls", e);
}
Expand All @@ -92,7 +94,7 @@ private static void loadFairySouls() {
}

private static void saveFoundFairySouls(MinecraftClient client) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(SkyblockerMod.CONFIG_DIR.resolve("found_fairy_souls.json").toFile()))) {
try (BufferedWriter writer = Files.newBufferedWriter(SkyblockerMod.CONFIG_DIR.resolve("found_fairy_souls.json"))) {
JsonObject foundFairiesJson = new JsonObject();
for (Map.Entry<String, Map<String, Set<BlockPos>>> foundFairiesForProfile : foundFairies.entrySet()) {
JsonObject foundFairiesForProfileJson = new JsonObject();
Expand All @@ -106,7 +108,6 @@ private static void saveFoundFairySouls(MinecraftClient client) {
foundFairiesJson.add(foundFairiesForProfile.getKey(), foundFairiesForProfileJson);
}
SkyblockerMod.GSON.toJson(foundFairiesJson, writer);
writer.close();
LOGGER.info("[Skyblocker] Saved found fairy souls");
} catch (IOException e) {
LOGGER.error("[Skyblocker] Failed to write found fairy souls to file", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@

import java.io.*;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
Expand All @@ -30,7 +33,7 @@

public class Shortcuts {
private static final Logger LOGGER = LoggerFactory.getLogger(Shortcuts.class);
private static final File SHORTCUTS_FILE = SkyblockerMod.CONFIG_DIR.resolve("shortcuts.json").toFile();
private static final Path SHORTCUTS_FILE = SkyblockerMod.CONFIG_DIR.resolve("shortcuts.json");
@Nullable
private static CompletableFuture<Void> shortcutsLoaded;
public static final Map<String, String> commands = new HashMap<>();
Expand All @@ -52,7 +55,7 @@ protected static void loadShortcuts() {
return;
}
shortcutsLoaded = CompletableFuture.runAsync(() -> {
try (BufferedReader reader = new BufferedReader(new FileReader(SHORTCUTS_FILE))) {
try (BufferedReader reader = Files.newBufferedReader(SHORTCUTS_FILE)) {
Type shortcutsType = new TypeToken<Map<String, Map<String, String>>>() {
}.getType();
Map<String, Map<String, String>> shortcuts = SkyblockerMod.GSON.fromJson(reader, shortcutsType);
Expand All @@ -61,7 +64,7 @@ protected static void loadShortcuts() {
commands.putAll(shortcuts.get("commands"));
commandArgs.putAll(shortcuts.get("commandArgs"));
LOGGER.info("[Skyblocker] Loaded {} command shortcuts and {} command argument shortcuts", commands.size(), commandArgs.size());
} catch (FileNotFoundException e) {
} catch (NoSuchFileException e) {
registerDefaultShortcuts();
LOGGER.warn("[Skyblocker] Shortcuts file not found, using default shortcuts. This is normal when using for the first time.");
} catch (IOException e) {
Expand Down Expand Up @@ -140,7 +143,7 @@ protected static void saveShortcuts(MinecraftClient client) {
JsonObject shortcutsJson = new JsonObject();
shortcutsJson.add("commands", SkyblockerMod.GSON.toJsonTree(commands));
shortcutsJson.add("commandArgs", SkyblockerMod.GSON.toJsonTree(commandArgs));
try (BufferedWriter writer = new BufferedWriter(new FileWriter(SHORTCUTS_FILE))) {
try (BufferedWriter writer = Files.newBufferedWriter(SHORTCUTS_FILE)) {
SkyblockerMod.GSON.toJson(shortcutsJson, writer);
LOGGER.info("[Skyblocker] Saved {} command shortcuts and {} command argument shortcuts", commands.size(), commandArgs.size());
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.util.*;
import java.util.concurrent.CompletableFuture;

Expand Down Expand Up @@ -68,7 +70,7 @@ private static void loadRelics(MinecraftClient client) {
LOGGER.error("[Skyblocker] Failed to load relics locations", e);
}

try (BufferedReader reader = new BufferedReader(new FileReader(SkyblockerMod.CONFIG_DIR.resolve("found_relics.json").toFile()))) {
try (BufferedReader reader = Files.newBufferedReader(SkyblockerMod.CONFIG_DIR.resolve("found_relics.json"))) {
for (Map.Entry<String, JsonElement> profileJson : JsonParser.parseReader(reader).getAsJsonObject().asMap().entrySet()) {
Set<BlockPos> foundRelicsForProfile = new HashSet<>();
for (JsonElement foundRelicsJson : profileJson.getValue().getAsJsonArray().asList()) {
Expand All @@ -77,15 +79,15 @@ private static void loadRelics(MinecraftClient client) {
foundRelics.put(profileJson.getKey(), foundRelicsForProfile);
}
LOGGER.debug("[Skyblocker] Loaded found relics");
} catch (FileNotFoundException ignored) {
} catch (NoSuchFileException ignored) {
} catch (IOException e) {
LOGGER.error("[Skyblocker] Failed to load found relics", e);
}
});
}

private static void saveFoundRelics(MinecraftClient client) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(SkyblockerMod.CONFIG_DIR.resolve("found_relics.json").toFile()))) {
try (BufferedWriter writer = Files.newBufferedWriter(SkyblockerMod.CONFIG_DIR.resolve("found_relics.json"))) {
JsonObject json = new JsonObject();
for (Map.Entry<String, Set<BlockPos>> foundRelicsForProfile : foundRelics.entrySet()) {
JsonArray foundRelicsJson = new JsonArray();
Expand Down
23 changes: 14 additions & 9 deletions src/main/java/de/hysky/skyblocker/utils/NEURepoManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;

/**
* Initializes the NEU repo, which contains item metadata and fairy souls location data. Clones the repo if it does not exist and checks for updates. Use {@link #runAsyncAfterLoad(Runnable)} to run code after the repo is initialized.
Expand Down Expand Up @@ -74,8 +76,7 @@ private static void deleteAndDownloadRepository() {
CompletableFuture.runAsync(() -> {
try {
ItemRepository.setFilesImported(false);
File dir = NEURepoManager.LOCAL_REPO_DIR.toFile();
recursiveDelete(dir);
recursiveDelete(NEURepoManager.LOCAL_REPO_DIR);
} catch (Exception ex) {
if (MinecraftClient.getInstance().player != null)
MinecraftClient.getInstance().player.sendMessage(Constants.PREFIX.get().append(Text.translatable("skyblocker.updaterepository.failed")), false);
Expand All @@ -86,14 +87,18 @@ private static void deleteAndDownloadRepository() {
}

@SuppressWarnings("ResultOfMethodCallIgnored")
private static void recursiveDelete(File dir) {
File[] children;
if (dir.isDirectory() && !Files.isSymbolicLink(dir.toPath()) && (children = dir.listFiles()) != null) {
for (File child : children) {
recursiveDelete(child);
}
private static void recursiveDelete(Path dir) throws IOException {
if (Files.isDirectory(dir) && !Files.isSymbolicLink(dir)) {
Files.list(dir).forEach(child -> {
try {
recursiveDelete(child);
} catch (Exception e) {
LOGGER.error("[Skyblocker] Encountered an exception while deleting a file! Path: {}", child.toAbsolutePath(), e);
}
});
}
dir.delete();

Files.delete(dir);
}

/**
Expand Down

0 comments on commit d8bd4d6

Please sign in to comment.