From 715f7b6a2e3d2a4d64012eb8d3628ebbca03cdba Mon Sep 17 00:00:00 2001 From: Pahimar Date: Wed, 18 May 2016 20:54:04 -0400 Subject: [PATCH] Still working on clearing out some cobwebs --- .../ee3/exchange/EnergyValueRegistry.java | 81 ++-------------- .../test/EnergyValueMappingsTestSuite.java | 95 ++++++++---------- .../pahimar/ee3/util/SerializationHelper.java | 97 ++++++++++++++++++- .../serialize/WrappedStackSerializer.java | 50 +++------- 4 files changed, 158 insertions(+), 165 deletions(-) diff --git a/src/main/java/com/pahimar/ee3/exchange/EnergyValueRegistry.java b/src/main/java/com/pahimar/ee3/exchange/EnergyValueRegistry.java index 9ab72e82..c858062c 100644 --- a/src/main/java/com/pahimar/ee3/exchange/EnergyValueRegistry.java +++ b/src/main/java/com/pahimar/ee3/exchange/EnergyValueRegistry.java @@ -2,7 +2,6 @@ package com.pahimar.ee3.exchange; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedMap; -import com.google.gson.JsonParseException; import com.pahimar.ee3.api.event.EnergyValueEvent; import com.pahimar.ee3.api.exchange.EnergyValue; import com.pahimar.ee3.api.exchange.IEnergyValueProvider; @@ -15,14 +14,14 @@ import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Loader; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; -import java.io.*; +import java.io.File; +import java.io.FileNotFoundException; import java.util.*; import static com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy.Phase; @@ -638,10 +637,10 @@ public class EnergyValueRegistry { * the local ones */ if (!loadedFromMap) { - writeToJsonFile(stackValueMap, energyValuesFile); + SerializationHelper.writeMapToFile(stackValueMap, energyValuesFile); } - writeToJsonFile(preCalculationStackValueMap, preCalculationValuesFile); - writeToJsonFile(postCalculationStackValueMap, postCalculationValuesFile); + SerializationHelper.writeMapToFile(preCalculationStackValueMap, preCalculationValuesFile); + SerializationHelper.writeMapToFile(postCalculationStackValueMap, postCalculationValuesFile); } /** @@ -653,20 +652,20 @@ public class EnergyValueRegistry { public void load() { try { - preCalculationStackValueMap.putAll(readFromJsonFile(preCalculationValuesFile)); + preCalculationStackValueMap.putAll(SerializationHelper.readMapFromFile(preCalculationValuesFile)); } catch (FileNotFoundException e) { // TODO Log that no pre-calculation values were loaded from file because file wasn't found } try { - postCalculationStackValueMap.putAll(readFromJsonFile(postCalculationValuesFile)); + postCalculationStackValueMap.putAll(SerializationHelper.readMapFromFile(postCalculationValuesFile)); } catch (FileNotFoundException e) { // TODO Log that no post-calculation values were loaded from file because file wasn't found } try { ImmutableSortedMap.Builder stackMapBuilder = ImmutableSortedMap.naturalOrder(); - stackMapBuilder.putAll(readFromJsonFile(energyValuesFile)); + stackMapBuilder.putAll(SerializationHelper.readMapFromFile(energyValuesFile)); stackValueMap = stackMapBuilder.build(); calculateValueStackMap(); } catch (FileNotFoundException e) { @@ -691,68 +690,4 @@ public class EnergyValueRegistry { calculateValueStackMap(); } } - - /** - * @see net.minecraft.nbt.CompressedStreamTools#safeWrite(NBTTagCompound, File) - */ - private static void writeToJsonFile(Map valueMap, File file) { - - File tempFile = new File(file.getAbsolutePath() + "_tmp"); - - if (tempFile.exists()) { - tempFile.delete(); - } - - try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tempFile))) { - - bufferedWriter.write(SerializationHelper.GSON.toJson(valueMap, SerializationHelper.ENERGY_VALUE_MAP_TYPE)); - bufferedWriter.close(); - } - catch (IOException exception) { - exception.printStackTrace(); // TODO Better logging of the exception - } - - if (file.exists()) { - file.delete(); - } - - if (file.exists()) { - LogHelper.warn("Failed to delete " + file); - } - else { - tempFile.renameTo(file); - } - } - - private static Map readFromJsonFile(File file) throws FileNotFoundException { - - Map valueMap = new TreeMap<>(); - - StringBuilder jsonStringBuilder = new StringBuilder(); - try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { - - jsonStringBuilder = new StringBuilder(); - String line; - while ((line = bufferedReader.readLine()) != null) { - jsonStringBuilder.append(line); - } - } - catch (IOException exception) { - if (exception instanceof FileNotFoundException) { - throw (FileNotFoundException) exception; - } - else { - exception.printStackTrace(); // TODO Better logging of the exception (other) - } - } - - try { - valueMap = SerializationHelper.GSON.fromJson(jsonStringBuilder.toString(), SerializationHelper.ENERGY_VALUE_MAP_TYPE); - } - catch (JsonParseException exception) { - // TODO Better logging of the exception (failed parsing so no values loaded) - } - - return valueMap; - } } diff --git a/src/main/java/com/pahimar/ee3/test/EnergyValueMappingsTestSuite.java b/src/main/java/com/pahimar/ee3/test/EnergyValueMappingsTestSuite.java index 77f9e461..d8b2fc06 100644 --- a/src/main/java/com/pahimar/ee3/test/EnergyValueMappingsTestSuite.java +++ b/src/main/java/com/pahimar/ee3/test/EnergyValueMappingsTestSuite.java @@ -24,30 +24,28 @@ public class EnergyValueMappingsTestSuite { public EnergyValueMappingsTestSuite() { - testSuiteValueMap = new TreeMap(); + testSuiteValueMap = new TreeMap<>(); } - public EnergyValueMappingsTestSuite(File jsonFile) - { - if (jsonFile != null && jsonFile.exists() && jsonFile.isFile()) - { + public EnergyValueMappingsTestSuite(File jsonFile) { + + if (jsonFile != null && jsonFile.exists() && jsonFile.isFile()) { testSuiteValueMap = SerializationHelper.readEnergyValueStackMapFromJsonFile(jsonFile); } } - public void add(Object object, Object value) - { - if (WrappedStack.canBeWrapped(object)) - { - if (value instanceof Number) - { + public void add(Object object, Object value) { + + if (WrappedStack.canBeWrapped(object)) { + + if (value instanceof Number) { Number number = (Number) value; WrappedStack wrappedStack = WrappedStack.wrap(object); wrappedStack.setStackSize(1); testSuiteValueMap.put(wrappedStack, new EnergyValue(number.floatValue())); } - else if (value == null) - { + else if (value == null) { + WrappedStack wrappedStack = WrappedStack.wrap(object); wrappedStack.setStackSize(1); testSuiteValueMap.put(wrappedStack, null); @@ -55,86 +53,77 @@ public class EnergyValueMappingsTestSuite { } } - public void remove(Object object) - { - if (WrappedStack.canBeWrapped(object)) - { + public void remove(Object object) { + + if (WrappedStack.canBeWrapped(object)) { WrappedStack wrappedStack = WrappedStack.wrap(object); wrappedStack.setStackSize(1); testSuiteValueMap.remove(wrappedStack); } } - public void loadTestSuite(File jsonFile) - { - if (jsonFile != null && jsonFile.exists() && jsonFile.isFile()) - { + public void loadTestSuite(File jsonFile) { + + if (jsonFile != null && jsonFile.exists() && jsonFile.isFile()) { testSuiteValueMap = SerializationHelper.readEnergyValueStackMapFromJsonFile(jsonFile); } } - public void saveTestSuite(File jsonFile) - { - if (jsonFile != null) - { + public void saveTestSuite(File jsonFile) { + + if (jsonFile != null) { SerializationHelper.writeEnergyValueStackMapToJsonFile(jsonFile, testSuiteValueMap); } } - public void runTestSuite() - { + public void runTestSuite() { runTestSuite(false); } - public void runTestSuite(boolean strict) - { - List successMessages = new ArrayList(); - List failureMessages = new ArrayList(); - for (WrappedStack wrappedStack : testSuiteValueMap.keySet()) - { - EnergyValue registryEnergyValue = EnergyValueRegistryProxy.getEnergyValue(wrappedStack, strict); - EnergyValue testSuiteEnergryValue = testSuiteValueMap.get(wrappedStack); + public void runTestSuite(boolean strict) { - if (registryEnergyValue == null && testSuiteEnergryValue == null) - { + List successMessages = new ArrayList<>(); + List failureMessages = new ArrayList<>(); + + for (WrappedStack wrappedStack : testSuiteValueMap.keySet()) { + + EnergyValue registryEnergyValue = EnergyValueRegistryProxy.getEnergyValue(wrappedStack, strict); + EnergyValue testSuiteEnergyValue = testSuiteValueMap.get(wrappedStack); + + if (registryEnergyValue == null && testSuiteEnergyValue == null) { /** * Success - anticipated that no value was found and no value was found */ - successMessages.add(String.format("SUCCESS: Object '%s' had the expected energy value [Expected (%s), Found (%s)]", wrappedStack, testSuiteEnergryValue, registryEnergyValue)); + successMessages.add(String.format("SUCCESS: Object '%s' had the expected energy value [Expected (%s), Found (%s)]", wrappedStack, testSuiteEnergyValue, registryEnergyValue)); } - else if (registryEnergyValue == null) - { + else if (registryEnergyValue == null) { /** * Failure - anticipated that a value would be found but no value was found */ - failureMessages.add(String.format("FAILURE: Object '%s' did not have the expected energy value [Expected (%s), Found (%s)]", wrappedStack, testSuiteEnergryValue, registryEnergyValue)); + failureMessages.add(String.format("FAILURE: Object '%s' did not have the expected energy value [Expected (%s), Found (%s)]", wrappedStack, testSuiteEnergyValue, registryEnergyValue)); } - else if (registryEnergyValue != null && testSuiteEnergryValue != null) - { - if (registryEnergyValue.equals(testSuiteEnergryValue)) - { + else if (registryEnergyValue != null && testSuiteEnergyValue != null) { + + if (registryEnergyValue.equals(testSuiteEnergyValue)) { /** * Success - anticipated that a specific value would be found and the anticipated value was found */ - successMessages.add(String.format("SUCCESS: Object '%s' had the expected energy value [Expected (%s), Found (%s)]", wrappedStack, testSuiteEnergryValue, registryEnergyValue)); + successMessages.add(String.format("SUCCESS: Object '%s' had the expected energy value [Expected (%s), Found (%s)]", wrappedStack, testSuiteEnergyValue, registryEnergyValue)); } - else - { + else { /** * Failure - anticipated that a specific value would be found and while a value was found it was not the anticipated one */ - failureMessages.add(String.format("FAILURE: Object '%s' did not have the expected energy value [Expected (%s), Found (%s)]", wrappedStack, testSuiteEnergryValue, registryEnergyValue)); + failureMessages.add(String.format("FAILURE: Object '%s' did not have the expected energy value [Expected (%s), Found (%s)]", wrappedStack, testSuiteEnergyValue, registryEnergyValue)); } } } - for (String successMessage : successMessages) - { + for (String successMessage : successMessages) { LogHelper.info(SUCCESS_MARKER, successMessage); } - for (String failureMessage : failureMessages) - { + for (String failureMessage : failureMessages) { LogHelper.warn(FAILURE_MARKER, failureMessage); } } diff --git a/src/main/java/com/pahimar/ee3/util/SerializationHelper.java b/src/main/java/com/pahimar/ee3/util/SerializationHelper.java index 69adc8b0..6a9c2d50 100644 --- a/src/main/java/com/pahimar/ee3/util/SerializationHelper.java +++ b/src/main/java/com/pahimar/ee3/util/SerializationHelper.java @@ -3,6 +3,7 @@ package com.pahimar.ee3.util; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.pahimar.ee3.api.exchange.EnergyValue; @@ -19,11 +20,14 @@ import net.minecraftforge.fluids.FluidStack; import java.io.*; import java.lang.reflect.Type; import java.util.Map; +import java.util.Set; import java.util.TreeMap; +import java.util.TreeSet; public class SerializationHelper { public static final Type ENERGY_VALUE_MAP_TYPE = new TypeToken>(){}.getType(); + public static final Type WRAPPED_STACK_SET_TYPE = new TypeToken>(){}.getType(); public static final Gson GSON = new GsonBuilder() .setPrettyPrinting() .enableComplexMapKeySerialization() @@ -58,10 +62,11 @@ public class SerializationHelper { } /** + * TODO Move this to {@link com.pahimar.ee3.reference.Files} + * * Creates (if one does not exist already) and initializes a mod specific File reference inside of the current world's playerdata directory */ - public static void initModDataDirectories() - { + public static void initModDataDirectories() { instanceDataDirectory = new File(FMLCommonHandler.instance().getMinecraftServerInstance().getEntityWorld().getSaveHandler().getWorldDirectory(), "data" + File.separator + Reference.LOWERCASE_MOD_ID); instanceDataDirectory.mkdirs(); @@ -192,4 +197,92 @@ public class SerializationHelper { e.printStackTrace(); } } + + public static Set readSetFromFile(File file) throws FileNotFoundException { + + Set wrappedStackSet = new TreeSet<>(); + + try { + wrappedStackSet = GSON.fromJson(readJsonFile(file), WRAPPED_STACK_SET_TYPE); + } + catch (JsonParseException exception) { + // TODO Better logging of the exception (failed parsing so no values loaded) + } + + return wrappedStackSet; + } + + public static void writeSetToFile(Set wrappedStackSet, File file) { + writeJsonFile(file, GSON.toJson(wrappedStackSet)); + } + + public static Map readMapFromFile(File file) throws FileNotFoundException { + + Map valueMap = new TreeMap<>(); + + try { + valueMap = GSON.fromJson(readJsonFile(file), ENERGY_VALUE_MAP_TYPE); + } + catch (JsonParseException exception) { + // TODO Better logging of the exception (failed parsing so no values loaded) + } + + return valueMap; + } + + public static void writeMapToFile(Map valueMap, File file) { + writeJsonFile(file, GSON.toJson(valueMap, ENERGY_VALUE_MAP_TYPE)); + } + + private static String readJsonFile(File file) throws FileNotFoundException { + + StringBuilder jsonStringBuilder = new StringBuilder(); + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { + + jsonStringBuilder = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + jsonStringBuilder.append(line); + } + } + catch (IOException exception) { + if (exception instanceof FileNotFoundException) { + throw (FileNotFoundException) exception; + } + else { + exception.printStackTrace(); // TODO Better logging of the exception + } + } + + return jsonStringBuilder.toString(); + } + + private static void writeJsonFile(File file, String fileContents) { + + File tempFile = new File(file.getAbsolutePath() + "_tmp"); + + if (tempFile.exists()) { + tempFile.delete(); + } + + try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tempFile))) { + + bufferedWriter.write(fileContents); + bufferedWriter.close(); + } + catch (IOException exception) { + exception.printStackTrace(); // TODO Better logging of the exception + } + + if (file.exists()) { + file.delete(); + } + + if (file.exists()) { + LogHelper.warn("Failed to delete " + file); + } + else { + tempFile.renameTo(file); + } + } } diff --git a/src/main/java/com/pahimar/ee3/util/serialize/WrappedStackSerializer.java b/src/main/java/com/pahimar/ee3/util/serialize/WrappedStackSerializer.java index 5d42c204..bd56c746 100644 --- a/src/main/java/com/pahimar/ee3/util/serialize/WrappedStackSerializer.java +++ b/src/main/java/com/pahimar/ee3/util/serialize/WrappedStackSerializer.java @@ -3,7 +3,6 @@ package com.pahimar.ee3.util.serialize; import com.google.gson.*; import com.pahimar.ee3.exchange.OreStack; import com.pahimar.ee3.exchange.WrappedStack; -import com.pahimar.ee3.util.SerializationHelper; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; @@ -11,54 +10,31 @@ import java.lang.reflect.Type; public class WrappedStackSerializer implements JsonSerializer, JsonDeserializer { - private static final String DATA = "data"; - private static final String TYPE = "type"; - private static final String TYPE_ITEMSTACK = "itemstack"; - private static final String TYPE_ORESTACK = "orestack"; - private static final String TYPE_FLUIDSTACK = "fluidstack"; + private static final String TYPE_ITEM_STACK = "itemstack"; + private static final String TYPE_ORE_STACK = "orestack"; + private static final String TYPE_FLUID_STACK = "fluidstack"; @Override - // TODO Update deserialize to match up with new serialize method implementation public WrappedStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonObject()) { JsonObject jsonObject = json.getAsJsonObject(); - String type = null; + WrappedStack wrappedStack = null; - try { - if (jsonObject.get(TYPE).getAsJsonPrimitive().isString()) { - type = jsonObject.get(TYPE).getAsString(); - } + if (jsonObject.has(TYPE_ITEM_STACK)) { + wrappedStack = WrappedStack.wrap(context.deserialize(jsonObject.get(TYPE_ITEM_STACK), ItemStack.class)); } - catch (IllegalStateException exception) { + else if (jsonObject.has(TYPE_ORE_STACK)) { + wrappedStack = WrappedStack.wrap(context.deserialize(jsonObject.get(TYPE_ORE_STACK), OreStack.class)); + } + else if (jsonObject.has(TYPE_FLUID_STACK)) { + wrappedStack = WrappedStack.wrap(context.deserialize(jsonObject.get(TYPE_FLUID_STACK), FluidStack.class)); } - if (jsonObject.get(DATA).isJsonObject()) { - JsonObject data = jsonObject.getAsJsonObject(DATA); - - if (TYPE_ITEMSTACK.equalsIgnoreCase(type)) { - ItemStack itemStack = SerializationHelper.GSON.fromJson(data, ItemStack.class); - - if (itemStack != null) { - return WrappedStack.wrap(itemStack); - } - } - else if (TYPE_ORESTACK.equalsIgnoreCase(type)) { - OreStack oreStack = SerializationHelper.GSON.fromJson(data, OreStack.class); - - if (oreStack != null) { - return WrappedStack.wrap(oreStack); - } - } - else if (TYPE_FLUIDSTACK.equalsIgnoreCase(type)) { - FluidStack fluidStack = SerializationHelper.GSON.fromJson(data, FluidStack.class); - - if (fluidStack != null) { - return WrappedStack.wrap(fluidStack); - } - } + if (wrappedStack != null) { + return wrappedStack; } }