From 5f56b7cd096add31687b21bbb8b6be92a112e7c0 Mon Sep 17 00:00:00 2001 From: temp1011 <34900092+temp1011@users.noreply.github.com> Date: Sun, 2 Dec 2018 00:46:19 +0000 Subject: [PATCH] Add methods to allow loading json constants outside of _constants (#4975) * add interface methods for loading json constants from an arbitary file * use try-with-resources * don't make modders create jsoncontext, clean up resource use * very minor cleanup --- .../common/crafting/CraftingHelper.java | 255 ++++++++++-------- .../common/crafting/JsonContext.java | 2 +- .../debug/gameplay/ConstantLoadingTest.java | 70 +++++ .../stuff/someConstants.json | 8 + 4 files changed, 224 insertions(+), 111 deletions(-) create mode 100644 src/test/java/net/minecraftforge/debug/gameplay/ConstantLoadingTest.java create mode 100644 src/test/resources/assets/constantloadingtest/stuff/someConstants.json diff --git a/src/main/java/net/minecraftforge/common/crafting/CraftingHelper.java b/src/main/java/net/minecraftforge/common/crafting/CraftingHelper.java index 40c69bbf24..ced93b14d9 100644 --- a/src/main/java/net/minecraftforge/common/crafting/CraftingHelper.java +++ b/src/main/java/net/minecraftforge/common/crafting/CraftingHelper.java @@ -21,6 +21,7 @@ package net.minecraftforge.common.crafting; import java.io.BufferedReader; import java.io.File; +import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; @@ -28,7 +29,6 @@ import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -42,8 +42,6 @@ import java.util.function.Function; import javax.annotation.Nonnull; import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.Level; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -628,37 +626,35 @@ public class CraftingHelper { private static void loadFactories(ModContainer mod) { - FileSystem fs = null; - BufferedReader reader = null; + Path fPath = null; + JsonContext ctx = new JsonContext(mod.getModId()); try { - JsonContext ctx = new JsonContext(mod.getModId()); - Path fPath = null; if (mod.getSource().isFile()) { - fs = FileSystems.newFileSystem(mod.getSource().toPath(), null); - fPath = fs.getPath("/assets/" + ctx.getModId() + "/recipes/_factories.json"); + try (FileSystem fs = FileSystems.newFileSystem(mod.getSource().toPath(), null)) + { + fPath = fs.getPath("/assets/" + ctx.getModId() + "/recipes/_factories.json"); + } } else if (mod.getSource().isDirectory()) { fPath = mod.getSource().toPath().resolve("assets/" + ctx.getModId() + "/recipes/_factories.json"); } + if (fPath != null && Files.exists(fPath)) { - reader = Files.newBufferedReader(fPath); - JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class); - loadFactories(json, ctx); + try (BufferedReader reader = Files.newBufferedReader(fPath)) + { + JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class); + loadFactories(json, ctx); + } } } catch (IOException e) { e.printStackTrace(); } - finally - { - IOUtils.closeQuietly(fs); - IOUtils.closeQuietly(reader); - } } private static boolean loadRecipes(ModContainer mod) @@ -671,10 +667,8 @@ public class CraftingHelper { Path fPath = root.resolve("_constants.json"); if (fPath != null && Files.exists(fPath)) { - BufferedReader reader = null; - try + try(BufferedReader reader = Files.newBufferedReader(fPath)) { - reader = Files.newBufferedReader(fPath); JsonObject[] json = JsonUtils.fromJson(GSON, reader, JsonObject[].class); ctx.loadConstants(json); } @@ -683,10 +677,6 @@ public class CraftingHelper { FMLLog.log.error("Error loading _constants.json: ", e); return false; } - finally - { - IOUtils.closeQuietly(reader); - } } return true; }, @@ -701,10 +691,8 @@ public class CraftingHelper { String name = FilenameUtils.removeExtension(relative).replaceAll("\\\\", "/"); ResourceLocation key = new ResourceLocation(ctx.getModId(), name); - BufferedReader reader = null; - try + try(BufferedReader reader = Files.newBufferedReader(file)) { - reader = Files.newBufferedReader(file); JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class); if (json.has("conditions") && !CraftingHelper.processConditions(JsonUtils.getJsonArray(json, "conditions"), ctx)) return true; @@ -721,10 +709,6 @@ public class CraftingHelper { FMLLog.log.error("Couldn't read recipe {} from {}", key, file, e); return false; } - finally - { - IOUtils.closeQuietly(reader); - } return true; }, true, true @@ -749,94 +733,145 @@ public class CraftingHelper { return findFiles(mod, base, preprocessor, processor, defaultUnfoundRoot, false); } - public static boolean findFiles(ModContainer mod, String base, Function preprocessor, BiFunction processor, boolean defaultUnfoundRoot, boolean visitAllFiles) + public static boolean findFiles(ModContainer mod, String base, Function preprocessor, BiFunction processor, + boolean defaultUnfoundRoot, boolean visitAllFiles) { - FileSystem fs = null; - try + + File source = mod.getSource(); + + if ("minecraft".equals(mod.getModId())) { - File source = mod.getSource(); + if (!DEBUG_LOAD_MINECRAFT) + return true; - if ("minecraft".equals(mod.getModId())) + try { - if (!DEBUG_LOAD_MINECRAFT) - return true; - - try - { - URI tmp = CraftingManager.class.getResource("/assets/.mcassetsroot").toURI(); - source = new File(tmp.resolve("..").getPath()); - } - catch (URISyntaxException e) - { - FMLLog.log.error("Error finding Minecraft jar: ", e); - return false; - } + URI tmp = CraftingManager.class.getResource("/assets/.mcassetsroot").toURI(); + source = new File(tmp.resolve("..").getPath()); } - - Path root = null; - if (source.isFile()) + catch (URISyntaxException e) { - try - { - fs = FileSystems.newFileSystem(source.toPath(), null); - root = fs.getPath("/" + base); - } - catch (IOException e) - { - FMLLog.log.error("Error loading FileSystem from jar: ", e); - return false; - } + FMLLog.log.error("Error finding Minecraft jar: ", e); + return false; } - else if (source.isDirectory()) - { - root = source.toPath().resolve(base); - } - - if (root == null || !Files.exists(root)) - return defaultUnfoundRoot; - - if (preprocessor != null) - { - Boolean cont = preprocessor.apply(root); - if (cont == null || !cont.booleanValue()) - return false; - } - - boolean success = true; - - if (processor != null) - { - Iterator itr = null; - try - { - itr = Files.walk(root).iterator(); - } - catch (IOException e) - { - FMLLog.log.error("Error iterating filesystem for: {}", mod.getModId(), e); - return false; - } - - while (itr != null && itr.hasNext()) - { - Boolean cont = processor.apply(root, itr.next()); - - if (visitAllFiles) - { - success &= cont != null && cont; - } - else if (cont == null || !cont) - { - return false; - } - } - } - - return success; } - finally + + Path root = null; + if (source.isFile()) { - IOUtils.closeQuietly(fs); + try (FileSystem fs = FileSystems.newFileSystem(source.toPath(), null);) + { + root = fs.getPath("/" + base); + } + catch (IOException e) + { + FMLLog.log.error("Error loading FileSystem from jar: ", e); + return false; + } + } + else if (source.isDirectory()) + { + root = source.toPath().resolve(base); + } + + if (root == null || !Files.exists(root)) + return defaultUnfoundRoot; + + if (preprocessor != null) + { + Boolean cont = preprocessor.apply(root); + if (cont == null || !cont.booleanValue()) + return false; + } + + boolean success = true; + + if (processor != null) + { + Iterator itr = null; + try + { + itr = Files.walk(root).iterator(); + } + catch (IOException e) + { + FMLLog.log.error("Error iterating filesystem for: {}", mod.getModId(), e); + return false; + } + + while (itr != null && itr.hasNext()) + { + Boolean cont = processor.apply(root, itr.next()); + + if (visitAllFiles) + { + success &= cont != null && cont; + } + else if (cont == null || !cont) + { + return false; + } + } + } + + return success; + } + + public static JsonContext loadContext(File file) throws IOException + { + ModContainer mod = Loader.instance().activeModContainer(); + if(mod == null) + { + throw new RuntimeException("Error loading constants, no mod to load for found"); + } + return loadContext(new JsonContext(mod.getModId()), file); + } + + public static JsonContext loadContext(String path) throws IOException + { + ModContainer mod = Loader.instance().activeModContainer(); + if(mod == null) + { + throw new RuntimeException("Error loading constants, no mod to load for found"); + } + return loadContext(mod, new JsonContext(mod.getModId()), path); + } + + private static JsonContext loadContext(JsonContext ctx, File file) throws IOException + { + try(BufferedReader reader = new BufferedReader(new FileReader(file))) + { + JsonObject[] json = JsonUtils.fromJson(GSON, reader, JsonObject[].class); + ctx.loadConstants(json); + return ctx; + } + catch (IOException e) + { + FMLLog.log.error("Error loading constants from file: {}", file.getAbsolutePath(), e); + throw e; + } + } + + private static JsonContext loadContext(ModContainer mod, JsonContext ctx, String path) throws IOException + { + Path fPath = null; + if(mod.getSource().isFile()) + { + try(FileSystem fs = FileSystems.newFileSystem(mod.getSource().toPath(), null)) + { + fPath = fs.getPath("/assets/" + ctx.getModId() + path); + } + } + else if (mod.getSource().isDirectory()) + { + fPath = mod.getSource().toPath().resolve("assets/" + ctx.getModId() + path); + } + + if (fPath != null && Files.exists(fPath)) + { + return loadContext(ctx, fPath.toFile()); + } else { + throw new IOException("path could not be resolved: " + path); } } } diff --git a/src/main/java/net/minecraftforge/common/crafting/JsonContext.java b/src/main/java/net/minecraftforge/common/crafting/JsonContext.java index 196842cada..49159987b0 100644 --- a/src/main/java/net/minecraftforge/common/crafting/JsonContext.java +++ b/src/main/java/net/minecraftforge/common/crafting/JsonContext.java @@ -58,7 +58,7 @@ public class JsonContext return constants.get(name); } - void loadConstants(JsonObject[] jsons) + void loadConstants(JsonObject... jsons) { for (JsonObject json : jsons) { diff --git a/src/test/java/net/minecraftforge/debug/gameplay/ConstantLoadingTest.java b/src/test/java/net/minecraftforge/debug/gameplay/ConstantLoadingTest.java new file mode 100644 index 0000000000..1ee5cba265 --- /dev/null +++ b/src/test/java/net/minecraftforge/debug/gameplay/ConstantLoadingTest.java @@ -0,0 +1,70 @@ +/* + * Minecraft Forge + * Copyright (c) 2016-2018. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.debug.gameplay; + +import java.io.IOException; + +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.Ingredient; +import net.minecraftforge.common.crafting.CraftingHelper; +import net.minecraftforge.common.crafting.JsonContext; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.Mod.EventHandler; +import net.minecraftforge.fml.common.event.FMLInitializationEvent; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +@Mod(modid = ConstantLoadingTest.MODID, name = "ConstantLoadingTestMod", version = "1.0", acceptableRemoteVersions = "*") +@Mod.EventBusSubscriber +public class ConstantLoadingTest +{ + public static final String MODID = "constantloadingtest"; + private static final boolean ENABLED = false; + + private static final Logger LOGGER = LogManager.getLogger(MODID); + + @EventHandler + public void init(FMLInitializationEvent event) + { + if (!ENABLED) + { + return; + } + LOGGER.info("Loading constant for recipe..."); + JsonContext ctx = null; + try + { + ctx = CraftingHelper.loadContext("/stuff/someConstants.json"); + } catch (IOException e) { + LOGGER.error("Something went wrong in loading the constant"); + return; + } + + Ingredient flint = ctx.getConstant("FLINT"); + if (flint == null) + { + LOGGER.error("Ingredients not loaded correctly from json"); + return; + } + LOGGER.info("Ingredient matches correctly: {}", flint.apply(new ItemStack(Items.FLINT))); + } +} diff --git a/src/test/resources/assets/constantloadingtest/stuff/someConstants.json b/src/test/resources/assets/constantloadingtest/stuff/someConstants.json new file mode 100644 index 0000000000..2b5301ea22 --- /dev/null +++ b/src/test/resources/assets/constantloadingtest/stuff/someConstants.json @@ -0,0 +1,8 @@ +[ + { + "ingredient": { + "item": "minecraft:flint" + }, + "name": "FLINT" + } +] \ No newline at end of file