Still working on clearing out some cobwebs

This commit is contained in:
Pahimar 2016-05-18 20:54:04 -04:00
parent f3011f091c
commit 715f7b6a2e
4 changed files with 158 additions and 165 deletions

View file

@ -2,7 +2,6 @@ package com.pahimar.ee3.exchange;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedMap;
import com.google.gson.JsonParseException;
import com.pahimar.ee3.api.event.EnergyValueEvent; import com.pahimar.ee3.api.event.EnergyValueEvent;
import com.pahimar.ee3.api.exchange.EnergyValue; import com.pahimar.ee3.api.exchange.EnergyValue;
import com.pahimar.ee3.api.exchange.IEnergyValueProvider; import com.pahimar.ee3.api.exchange.IEnergyValueProvider;
@ -15,14 +14,14 @@ import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Loader;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreDictionary;
import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager; import org.apache.logging.log4j.MarkerManager;
import java.io.*; import java.io.File;
import java.io.FileNotFoundException;
import java.util.*; import java.util.*;
import static com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy.Phase; import static com.pahimar.ee3.api.exchange.EnergyValueRegistryProxy.Phase;
@ -638,10 +637,10 @@ public class EnergyValueRegistry {
* the local ones * the local ones
*/ */
if (!loadedFromMap) { if (!loadedFromMap) {
writeToJsonFile(stackValueMap, energyValuesFile); SerializationHelper.writeMapToFile(stackValueMap, energyValuesFile);
} }
writeToJsonFile(preCalculationStackValueMap, preCalculationValuesFile); SerializationHelper.writeMapToFile(preCalculationStackValueMap, preCalculationValuesFile);
writeToJsonFile(postCalculationStackValueMap, postCalculationValuesFile); SerializationHelper.writeMapToFile(postCalculationStackValueMap, postCalculationValuesFile);
} }
/** /**
@ -653,20 +652,20 @@ public class EnergyValueRegistry {
public void load() { public void load() {
try { try {
preCalculationStackValueMap.putAll(readFromJsonFile(preCalculationValuesFile)); preCalculationStackValueMap.putAll(SerializationHelper.readMapFromFile(preCalculationValuesFile));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
// TODO Log that no pre-calculation values were loaded from file because file wasn't found // TODO Log that no pre-calculation values were loaded from file because file wasn't found
} }
try { try {
postCalculationStackValueMap.putAll(readFromJsonFile(postCalculationValuesFile)); postCalculationStackValueMap.putAll(SerializationHelper.readMapFromFile(postCalculationValuesFile));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
// TODO Log that no post-calculation values were loaded from file because file wasn't found // TODO Log that no post-calculation values were loaded from file because file wasn't found
} }
try { try {
ImmutableSortedMap.Builder<WrappedStack, EnergyValue> stackMapBuilder = ImmutableSortedMap.naturalOrder(); ImmutableSortedMap.Builder<WrappedStack, EnergyValue> stackMapBuilder = ImmutableSortedMap.naturalOrder();
stackMapBuilder.putAll(readFromJsonFile(energyValuesFile)); stackMapBuilder.putAll(SerializationHelper.readMapFromFile(energyValuesFile));
stackValueMap = stackMapBuilder.build(); stackValueMap = stackMapBuilder.build();
calculateValueStackMap(); calculateValueStackMap();
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
@ -691,68 +690,4 @@ public class EnergyValueRegistry {
calculateValueStackMap(); calculateValueStackMap();
} }
} }
/**
* @see net.minecraft.nbt.CompressedStreamTools#safeWrite(NBTTagCompound, File)
*/
private static void writeToJsonFile(Map<WrappedStack, EnergyValue> 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<WrappedStack, EnergyValue> readFromJsonFile(File file) throws FileNotFoundException {
Map<WrappedStack, EnergyValue> 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;
}
} }

View file

@ -24,30 +24,28 @@ public class EnergyValueMappingsTestSuite {
public EnergyValueMappingsTestSuite() public EnergyValueMappingsTestSuite()
{ {
testSuiteValueMap = new TreeMap<WrappedStack, EnergyValue>(); testSuiteValueMap = new TreeMap<>();
} }
public EnergyValueMappingsTestSuite(File jsonFile) public EnergyValueMappingsTestSuite(File jsonFile) {
{
if (jsonFile != null && jsonFile.exists() && jsonFile.isFile()) if (jsonFile != null && jsonFile.exists() && jsonFile.isFile()) {
{
testSuiteValueMap = SerializationHelper.readEnergyValueStackMapFromJsonFile(jsonFile); testSuiteValueMap = SerializationHelper.readEnergyValueStackMapFromJsonFile(jsonFile);
} }
} }
public void add(Object object, Object value) public void add(Object object, Object value) {
{
if (WrappedStack.canBeWrapped(object)) if (WrappedStack.canBeWrapped(object)) {
{
if (value instanceof Number) if (value instanceof Number) {
{
Number number = (Number) value; Number number = (Number) value;
WrappedStack wrappedStack = WrappedStack.wrap(object); WrappedStack wrappedStack = WrappedStack.wrap(object);
wrappedStack.setStackSize(1); wrappedStack.setStackSize(1);
testSuiteValueMap.put(wrappedStack, new EnergyValue(number.floatValue())); testSuiteValueMap.put(wrappedStack, new EnergyValue(number.floatValue()));
} }
else if (value == null) else if (value == null) {
{
WrappedStack wrappedStack = WrappedStack.wrap(object); WrappedStack wrappedStack = WrappedStack.wrap(object);
wrappedStack.setStackSize(1); wrappedStack.setStackSize(1);
testSuiteValueMap.put(wrappedStack, null); testSuiteValueMap.put(wrappedStack, null);
@ -55,86 +53,77 @@ public class EnergyValueMappingsTestSuite {
} }
} }
public void remove(Object object) public void remove(Object object) {
{
if (WrappedStack.canBeWrapped(object)) if (WrappedStack.canBeWrapped(object)) {
{
WrappedStack wrappedStack = WrappedStack.wrap(object); WrappedStack wrappedStack = WrappedStack.wrap(object);
wrappedStack.setStackSize(1); wrappedStack.setStackSize(1);
testSuiteValueMap.remove(wrappedStack); testSuiteValueMap.remove(wrappedStack);
} }
} }
public void loadTestSuite(File jsonFile) public void loadTestSuite(File jsonFile) {
{
if (jsonFile != null && jsonFile.exists() && jsonFile.isFile()) if (jsonFile != null && jsonFile.exists() && jsonFile.isFile()) {
{
testSuiteValueMap = SerializationHelper.readEnergyValueStackMapFromJsonFile(jsonFile); testSuiteValueMap = SerializationHelper.readEnergyValueStackMapFromJsonFile(jsonFile);
} }
} }
public void saveTestSuite(File jsonFile) public void saveTestSuite(File jsonFile) {
{
if (jsonFile != null) if (jsonFile != null) {
{
SerializationHelper.writeEnergyValueStackMapToJsonFile(jsonFile, testSuiteValueMap); SerializationHelper.writeEnergyValueStackMapToJsonFile(jsonFile, testSuiteValueMap);
} }
} }
public void runTestSuite() public void runTestSuite() {
{
runTestSuite(false); runTestSuite(false);
} }
public void runTestSuite(boolean strict) public void runTestSuite(boolean strict) {
{
List<String> successMessages = new ArrayList<String>();
List<String> failureMessages = new ArrayList<String>();
for (WrappedStack wrappedStack : testSuiteValueMap.keySet())
{
EnergyValue registryEnergyValue = EnergyValueRegistryProxy.getEnergyValue(wrappedStack, strict);
EnergyValue testSuiteEnergryValue = testSuiteValueMap.get(wrappedStack);
if (registryEnergyValue == null && testSuiteEnergryValue == null) List<String> successMessages = new ArrayList<>();
{ List<String> 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 * 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 * 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) else if (registryEnergyValue != null && testSuiteEnergyValue != null) {
{
if (registryEnergyValue.equals(testSuiteEnergryValue)) if (registryEnergyValue.equals(testSuiteEnergyValue)) {
{
/** /**
* Success - anticipated that a specific value would be found and the anticipated value was found * 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 * 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); LogHelper.info(SUCCESS_MARKER, successMessage);
} }
for (String failureMessage : failureMessages) for (String failureMessage : failureMessages) {
{
LogHelper.warn(FAILURE_MARKER, failureMessage); LogHelper.warn(FAILURE_MARKER, failureMessage);
} }
} }

View file

@ -3,6 +3,7 @@ package com.pahimar.ee3.util;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter; import com.google.gson.stream.JsonWriter;
import com.pahimar.ee3.api.exchange.EnergyValue; import com.pahimar.ee3.api.exchange.EnergyValue;
@ -19,11 +20,14 @@ import net.minecraftforge.fluids.FluidStack;
import java.io.*; import java.io.*;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.TreeSet;
public class SerializationHelper { public class SerializationHelper {
public static final Type ENERGY_VALUE_MAP_TYPE = new TypeToken<Map<WrappedStack, EnergyValue>>(){}.getType(); public static final Type ENERGY_VALUE_MAP_TYPE = new TypeToken<Map<WrappedStack, EnergyValue>>(){}.getType();
public static final Type WRAPPED_STACK_SET_TYPE = new TypeToken<Set<WrappedStack>>(){}.getType();
public static final Gson GSON = new GsonBuilder() public static final Gson GSON = new GsonBuilder()
.setPrettyPrinting() .setPrettyPrinting()
.enableComplexMapKeySerialization() .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 * 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 = new File(FMLCommonHandler.instance().getMinecraftServerInstance().getEntityWorld().getSaveHandler().getWorldDirectory(), "data" + File.separator + Reference.LOWERCASE_MOD_ID);
instanceDataDirectory.mkdirs(); instanceDataDirectory.mkdirs();
@ -192,4 +197,92 @@ public class SerializationHelper {
e.printStackTrace(); e.printStackTrace();
} }
} }
public static Set<WrappedStack> readSetFromFile(File file) throws FileNotFoundException {
Set<WrappedStack> 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<WrappedStack> wrappedStackSet, File file) {
writeJsonFile(file, GSON.toJson(wrappedStackSet));
}
public static Map<WrappedStack, EnergyValue> readMapFromFile(File file) throws FileNotFoundException {
Map<WrappedStack, EnergyValue> 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<WrappedStack, EnergyValue> 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);
}
}
} }

View file

@ -3,7 +3,6 @@ package com.pahimar.ee3.util.serialize;
import com.google.gson.*; import com.google.gson.*;
import com.pahimar.ee3.exchange.OreStack; import com.pahimar.ee3.exchange.OreStack;
import com.pahimar.ee3.exchange.WrappedStack; import com.pahimar.ee3.exchange.WrappedStack;
import com.pahimar.ee3.util.SerializationHelper;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidStack;
@ -11,54 +10,31 @@ import java.lang.reflect.Type;
public class WrappedStackSerializer implements JsonSerializer<WrappedStack>, JsonDeserializer<WrappedStack> { public class WrappedStackSerializer implements JsonSerializer<WrappedStack>, JsonDeserializer<WrappedStack> {
private static final String DATA = "data"; private static final String TYPE_ITEM_STACK = "itemstack";
private static final String TYPE = "type"; private static final String TYPE_ORE_STACK = "orestack";
private static final String TYPE_ITEMSTACK = "itemstack"; private static final String TYPE_FLUID_STACK = "fluidstack";
private static final String TYPE_ORESTACK = "orestack";
private static final String TYPE_FLUIDSTACK = "fluidstack";
@Override @Override
// TODO Update deserialize to match up with new serialize method implementation
public WrappedStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public WrappedStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonObject()) { if (json.isJsonObject()) {
JsonObject jsonObject = json.getAsJsonObject(); JsonObject jsonObject = json.getAsJsonObject();
String type = null; WrappedStack wrappedStack = null;
try { if (jsonObject.has(TYPE_ITEM_STACK)) {
if (jsonObject.get(TYPE).getAsJsonPrimitive().isString()) { wrappedStack = WrappedStack.wrap(context.deserialize(jsonObject.get(TYPE_ITEM_STACK), ItemStack.class));
type = jsonObject.get(TYPE).getAsString();
}
} }
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()) { if (wrappedStack != null) {
JsonObject data = jsonObject.getAsJsonObject(DATA); return wrappedStack;
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);
}
}
} }
} }