Browse Source

Adds Post Deserialize

TomTroppmann 2 years ago
parent
commit
d679438a56

+ 4 - 2
src/holeg/model/AbstractCanvasObject.java

@@ -4,6 +4,7 @@ import holeg.ui.model.IdCounter;
 import holeg.utility.math.vector.Vec2i;
 
 import java.util.Optional;
+import java.util.logging.Logger;
 
 /**
  * The abstract class "CpsObject" represents any possible object in the system
@@ -13,10 +14,11 @@ import java.util.Optional;
  * @author Gruppe14
  */
 public abstract class AbstractCanvasObject {
+    private static final Logger log = Logger.getLogger(AbstractCanvasObject.class.getName());
     /* Name given by the user. */
-    String name;
+    String name = "";
     /* Path of the image for the Obj. */
-    String imagePath;
+    String imagePath = "";
     /* Position with a X and Y value */
     Vec2i position = new Vec2i(0, 0);
     /* ID of the Obj. */

+ 4 - 4
src/holeg/model/GroupNode.java

@@ -6,8 +6,9 @@ import java.util.logging.Logger;
 import java.util.stream.Stream;
 
 import holeg.preferences.ImagePreference;
+import holeg.serialize.PostDeserialize;
 
-public class GroupNode extends AbstractCanvasObject {
+public class GroupNode extends AbstractCanvasObject implements PostDeserialize {
 	private static final Logger log = Logger.getLogger(AbstractCanvasObject.class.getName());
 
 	private final ArrayList<HolonObject> objectList = new ArrayList<>();
@@ -121,9 +122,8 @@ public class GroupNode extends AbstractCanvasObject {
 		groupNodeList.clear();
 	}
 
-	public void updateReference() {
+	@Override
+	public void postDeserialize() {
 		getObjectsInThisLayer().forEach(obj -> obj.setGroupNode(this));
-		objectList.forEach(HolonObject::updateReference);
-		groupNodeList.forEach(GroupNode::updateReference);
 	}
 }

+ 14 - 11
src/holeg/model/HolonElement.java

@@ -2,8 +2,8 @@ package holeg.model;
 
 import holeg.interfaces.TimelineDependent;
 import holeg.model.Flexibility.FlexState;
+import holeg.serialize.PostDeserialize;
 import holeg.ui.controller.IndexTranslator;
-import holeg.ui.model.IdCounter;
 import holeg.utility.math.vector.Vec2f;
 
 import java.util.ArrayList;
@@ -18,7 +18,7 @@ import java.util.logging.Logger;
  *
  * @author Gruppe14
  */
-public class HolonElement implements TimelineDependent {
+public class HolonElement implements TimelineDependent, PostDeserialize {
     private static final Logger log = Logger.getLogger(HolonElement.class.getName());
     /**
      * Owner of the Element
@@ -27,7 +27,7 @@ public class HolonElement implements TimelineDependent {
     /**
      * Whether the gadget is active or not (currently uses/produces the energy in energyPerElement)
      */
-    public boolean active;
+    public boolean active = true;
     public Priority priority = Priority.Low;
     public List<Flexibility> flexList = new ArrayList<>();
     /**
@@ -66,16 +66,18 @@ public class HolonElement implements TimelineDependent {
     /**
      * same as standard constructor, but with already given id (so the counter is not increased twice)
      */
-    public HolonElement(HolonObject parentObject, String eleName, float energy) {
+    public HolonElement(HolonObject parentObject, String name, float energy) {
         this.parentObject = parentObject;
-        setName(eleName);
+        setName(name);
         setEnergy(energy);
-        this.active = true;
         initGraphPoints();
         sampleGraph();
     }
 
 
+
+
+
     /**
      * Create a copy of the HolonElement given each one a new ID.
      *
@@ -346,13 +348,14 @@ public class HolonElement implements TimelineDependent {
         return flexList.stream().anyMatch(flex -> flex.getState() == FlexState.IN_USE || flex.getState() == FlexState.ON_COOLDOWN);
     }
 
-    public enum Priority {
-        Low, Medium, High, Essential
+    @Override
+    public void postDeserialize() {
+        flexList.forEach(flex -> flex.setElement(this));
+        sampleGraph();
     }
 
-
-    public void updateReference(){
-        flexList.forEach(flex -> flex.setElement(this));
+    public enum Priority {
+        Low, Medium, High, Essential
     }
 
 }

+ 12 - 8
src/holeg/model/HolonObject.java

@@ -1,5 +1,7 @@
 package holeg.model;
 
+import holeg.serialize.PostDeserialize;
+
 import java.util.*;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
@@ -11,7 +13,7 @@ import java.util.stream.Stream;
  *
  * @author Gruppe14
  */
-public class HolonObject extends AbstractCanvasObject {
+public class HolonObject extends AbstractCanvasObject implements PostDeserialize {
     /* Array of all consumers */
     private final Set<HolonElement> elements = new HashSet<>();
 
@@ -35,6 +37,10 @@ public class HolonObject extends AbstractCanvasObject {
         super(objName);
     }
 
+
+
+
+
     /**
      * Contructor of a copy of an Object.
      *
@@ -258,15 +264,13 @@ public class HolonObject extends AbstractCanvasObject {
         }
     }
 
-    public enum HolonObjectState {
-        NO_ENERGY, NOT_SUPPLIED, SUPPLIED, PRODUCER, PARTIALLY_SUPPLIED, OVER_SUPPLIED
+    @Override
+    public void postDeserialize() {
+        elements.forEach(ele -> ele.parentObject = this);
     }
 
-    public void updateReference(){
-        elements.forEach(ele -> {
-            ele.parentObject = this;
-            ele.updateReference();
-        });
+    public enum HolonObjectState {
+        NO_ENERGY, NOT_SUPPLIED, SUPPLIED, PRODUCER, PARTIALLY_SUPPLIED, OVER_SUPPLIED
     }
 
 }

+ 7 - 1
src/holeg/model/HolonSwitch.java

@@ -3,6 +3,7 @@ package holeg.model;
 import holeg.interfaces.LocalMode;
 import holeg.interfaces.TimelineDependent;
 import holeg.preferences.ImagePreference;
+import holeg.serialize.PostDeserialize;
 import holeg.ui.controller.IndexTranslator;
 import holeg.utility.math.vector.Vec2f;
 
@@ -16,7 +17,7 @@ import java.util.ListIterator;
  *
  * @author Gruppe14
  */
-public class HolonSwitch extends AbstractCanvasObject implements TimelineDependent {
+public class HolonSwitch extends AbstractCanvasObject implements TimelineDependent, PostDeserialize {
     /**
      * Energy at each point of the graph with 50 predefined points. At the
      * beginning, it starts with all values at energy
@@ -200,6 +201,11 @@ public class HolonSwitch extends AbstractCanvasObject implements TimelineDepende
 
     }
 
+    @Override
+    public void postDeserialize() {
+        sampleGraph();
+    }
+
     public enum SwitchState {
         Open, Closed;
 

+ 98 - 94
src/holeg/preferences/ColorPreference.java

@@ -1,105 +1,109 @@
 package holeg.preferences;
 
-import java.awt.Color;
-
 import holeg.model.Flexibility.FlexState;
 import holeg.model.HolonObject.HolonObjectState;
 
+import java.awt.*;
+
 /**
  * A Class to save all colors in Holeg.
- * @author Tom
  *
+ * @author Tom
  */
 public class ColorPreference {
-	
-	
-	public static class Element{
-		public static class Priority{
-			public static final Color Essential = new Color(201, 44, 74);
-			public static final Color High = new Color(255, 92, 26);
-			public static final Color Medium = new Color(255, 216, 57);
-			public static final Color Low = new Color(255, 255, 175);
-			public static final Color NoData = new Color(21, 8, 17);
-		}
-		public static final Color Active = new Color(255, 203, 35);
-		public static final Color Inactive = new Color(128, 154, 163);
-	}
-	public static class HolonObject{
-		public static final Color Producer = new Color(149, 152, 159, 211);
-		public static final Color OverSupplied = new Color(166, 78, 229);
-		public static final Color Supplied = new Color(13, 175, 28);
-		public static final Color PartiallySupplied = new Color(255, 233, 1);
-		public static final Color NotSupplied = new Color(230, 120, 100);
-		public static final Color NoEnergy = new Color(211, 211, 211);
-	
-		public static Color getStateColor(HolonObjectState state) {
-			return switch (state) {
-				case NOT_SUPPLIED -> NotSupplied;
-				case OVER_SUPPLIED -> OverSupplied;
-				case PARTIALLY_SUPPLIED -> PartiallySupplied;
-				case PRODUCER -> Producer;
-				case SUPPLIED -> Supplied;
-				case NO_ENERGY -> NoEnergy;
-			};
-		}
-	}
-	
-	public static class Edge{
-		public static final Color Working = new Color(13, 175, 28);
-		public static final Color Burned = Color.red;
-	}
-	
-	
-	
-	public static class Energy{
-		public static final Color Production = new Color(61, 133, 243);
-		public static final Color Consumption = new Color(255, 67, 60);
-	}
-	public static class Flexibility{
-		public static final Color InUse = new Color(182, 238, 166);
-		public static final Color OnCooldown = new Color(239, 215, 128);
-		public static final Color Offered = new Color(75, 170, 72);
-		public static final Color NotOffered = new Color(237, 106, 90);
-		public static final Color Unavailable = new Color(193, 193, 193);
-		
-		public static Color getStateColor(FlexState state) {
-			return switch (state) {
-				case IN_USE -> InUse;
-				case NOT_OFFERED -> NotOffered;
-				case OFFERED -> Offered;
-				case ON_COOLDOWN -> OnCooldown;
-				case UNAVAILABLE -> Unavailable;
-			};
-		}
-	}
-	
-	public static class Panel {
-		public static final Color Transparent = new Color(0,0,0,0);
-		public static final Color Background = new Color(250, 250, 250);
-		public static final Color Title = new Color(54, 73, 78);
-	}
-	public static class Canvas {
-		public static final Color MouseSelectionBorder = new Color(0, 120, 215);
-		public static final Color MouseSelectionFill = new Color(128, 174, 247, 40);
-		public static final Color ObjectSelectionBorder = new Color(153, 209, 255);
-		public static final Color ObjectSelectionFill = new Color(205, 233, 255);
-	}
-
-
-	public static class Dialog{
-		public static final Color BackgroundColor = new Color(255, 50, 50);
-	}
-	
-	public static class Category {
-		public final static Color Focus = new Color(0, 0, 255);	
-	}
-	public static class Inspector{
-		public final static Color Selected = new Color(126, 186, 255);
-		public final static Color Border = new Color(171, 173, 179);
-	}
-	
-	public static class GUI {
-		//TODO(Tom2021-12-1) for what is this collor used
-		public static final Color PALE_RED = new Color(255, 192, 192);
-	}
+
+
+    public static class Element {
+        public static final Color Active = new Color(255, 203, 35);
+        public static final Color Inactive = new Color(128, 154, 163);
+
+        public static class Priority {
+            public static final Color Essential = new Color(201, 44, 74);
+            public static final Color High = new Color(255, 92, 26);
+            public static final Color Medium = new Color(255, 216, 57);
+            public static final Color Low = new Color(255, 255, 175);
+            public static final Color NoData = new Color(21, 8, 17);
+        }
+    }
+
+    public static class HolonObject {
+        public static final Color Producer = new Color(149, 152, 159, 211);
+        public static final Color OverSupplied = new Color(166, 78, 229);
+        public static final Color Supplied = new Color(13, 175, 28);
+        public static final Color PartiallySupplied = new Color(255, 233, 1);
+        public static final Color NotSupplied = new Color(230, 120, 100);
+        public static final Color NoEnergy = new Color(211, 211, 211);
+
+        public static Color getStateColor(HolonObjectState state) {
+            return switch (state) {
+                case NOT_SUPPLIED -> NotSupplied;
+                case OVER_SUPPLIED -> OverSupplied;
+                case PARTIALLY_SUPPLIED -> PartiallySupplied;
+                case PRODUCER -> Producer;
+                case SUPPLIED -> Supplied;
+                case NO_ENERGY -> NoEnergy;
+            };
+        }
+    }
+
+    public static class Edge {
+        public static final Color Working = new Color(13, 175, 28);
+        public static final Color Burned = Color.red;
+    }
+
+
+    public static class Energy {
+        public static final Color Production = new Color(61, 133, 243);
+        public static final Color Consumption = new Color(255, 67, 60);
+    }
+
+    public static class Flexibility {
+        public static final Color InUse = new Color(182, 238, 166);
+        public static final Color OnCooldown = new Color(239, 215, 128);
+        public static final Color Offered = new Color(75, 170, 72);
+        public static final Color NotOffered = new Color(237, 106, 90);
+        public static final Color Unavailable = new Color(193, 193, 193);
+
+        public static Color getStateColor(FlexState state) {
+            return switch (state) {
+                case IN_USE -> InUse;
+                case NOT_OFFERED -> NotOffered;
+                case OFFERED -> Offered;
+                case ON_COOLDOWN -> OnCooldown;
+                case UNAVAILABLE -> Unavailable;
+            };
+        }
+    }
+
+    public static class Panel {
+        public static final Color Transparent = new Color(0, 0, 0, 0);
+        public static final Color Background = new Color(250, 250, 250);
+        public static final Color Title = new Color(54, 73, 78);
+    }
+
+    public static class Canvas {
+        public static final Color MouseSelectionBorder = new Color(0, 120, 215);
+        public static final Color MouseSelectionFill = new Color(128, 174, 247, 40);
+        public static final Color ObjectSelectionBorder = new Color(153, 209, 255);
+        public static final Color ObjectSelectionFill = new Color(205, 233, 255);
+    }
+
+
+    public static class Dialog {
+        public static final Color BackgroundColor = new Color(255, 50, 50);
+    }
+
+    public static class Category {
+        public final static Color Focus = new Color(0, 0, 255);
+    }
+
+    public static class Inspector {
+        public final static Color Selected = new Color(126, 186, 255);
+        public final static Color Border = new Color(171, 173, 179);
+    }
+
+    public static class GUI {
+        //TODO(Tom2021-12-1) for what is this collor used
+        public static final Color PALE_RED = new Color(255, 192, 192);
+    }
 }

+ 1 - 2
src/holeg/adapter/EdgeDeserializer.java → src/holeg/serialize/EdgeDeserializer.java

@@ -1,10 +1,9 @@
-package holeg.adapter;
+package holeg.serialize;
 
 import com.google.gson.*;
 import holeg.model.AbstractCanvasObject;
 import holeg.model.Edge;
 
-import java.io.IOException;
 import java.lang.reflect.Type;
 import java.util.HashMap;
 import java.util.Map;

+ 1 - 2
src/holeg/adapter/EdgeSerializer.java → src/holeg/serialize/EdgeSerializer.java

@@ -1,4 +1,4 @@
-package holeg.adapter;
+package holeg.serialize;
 
 import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
@@ -6,7 +6,6 @@ import com.google.gson.JsonSerializationContext;
 import com.google.gson.JsonSerializer;
 import holeg.model.Edge;
 
-import java.io.IOException;
 import java.lang.reflect.Type;
 
 public class EdgeSerializer implements JsonSerializer<Edge> {

+ 20 - 0
src/holeg/serialize/GsonCollection.java

@@ -0,0 +1,20 @@
+package holeg.serialize;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import holeg.model.*;
+
+public class GsonCollection {
+    public static final Gson Gson = initGson();
+
+    private static Gson initGson() {
+        GsonBuilder builder = new GsonBuilder();
+        builder.registerTypeAdapter(Edge.class, new EdgeSerializer());
+        builder.registerTypeAdapter(Model.class, new ModelDeserializer());
+        builder.registerTypeAdapterFactory(new PostDeserializeEnabler());
+
+        builder.serializeNulls();
+        builder.setPrettyPrinting();
+        return builder.create();
+    }
+}

+ 13 - 11
src/holeg/adapter/ModelDeserializer.java → src/holeg/serialize/ModelDeserializer.java

@@ -1,4 +1,4 @@
-package holeg.adapter;
+package holeg.serialize;
 
 import com.google.gson.*;
 import com.google.gson.reflect.TypeToken;
@@ -11,28 +11,30 @@ import java.util.function.Function;
 import java.util.logging.Logger;
 import java.util.stream.Collectors;
 
-public class ModelDeserializer implements JsonDeserializer<Model> {
+public class ModelDeserializer implements JsonDeserializer<Model>{
     private static final Logger log = Logger.getLogger(ModelDeserializer.class.getName());
     private final static Type edgeSetType = TypeToken.getParameterized(HashSet.class, Edge.class).getType();
     private final EdgeDeserializer edgeDeserializer = new EdgeDeserializer();
-    private final Gson gson = new GsonBuilder().registerTypeAdapter(Edge.class, edgeDeserializer).create();
+    private final Gson edgeGson = new GsonBuilder().registerTypeAdapter(Edge.class, edgeDeserializer).create();
 
     @Override
     public Model deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
         log.info("ModelDeserializer");
-        final JsonObject jsonObj = json.getAsJsonObject();
+        JsonObject jsonObj = json.getAsJsonObject();
+
         Model model = new Model();
         GroupNode canvas = context.deserialize(jsonObj.getAsJsonObject("canvas"), GroupNode.class);
         model.setCanvas(canvas);
         edgeDeserializer.idMap = canvas.getAllObjectsRecursive()
                 .collect(Collectors.toMap(AbstractCanvasObject::getId, Function.identity()));
-        //TODO(Tom2022-01-27): COMBINE methods sampleGraph and updateReference in Interface
-        model.getAllHolonElements().forEach(HolonElement::sampleGraph);
-        model.getCanvas().getAllSwitchObjectsRecursive().forEach(HolonSwitch::sampleGraph);
-        model.getCanvas().updateReference();
-        model.setEdgesOnCanvas(gson.fromJson(jsonObj.getAsJsonArray("edgesOnCanvas"), edgeSetType));
-        model.getCanvas().getAllObjectsRecursive().mapToInt(AbstractCanvasObject::getId).max()
-                .ifPresent(maxId -> IdCounter.set(maxId + 1));
+        model.setEdgesOnCanvas(edgeGson.fromJson(jsonObj.getAsJsonArray("edgesOnCanvas"), edgeSetType));
+
+        updateIdCounter(model.getCanvas());
         return model;
     }
+
+    private void updateIdCounter(GroupNode canvas){
+        canvas.getAllObjectsRecursive().mapToInt(AbstractCanvasObject::getId).max()
+                .ifPresent(maxId -> IdCounter.set(maxId + 1));
+    }
 }

+ 5 - 0
src/holeg/serialize/PostDeserialize.java

@@ -0,0 +1,5 @@
+package holeg.serialize;
+
+public interface PostDeserialize {
+    void postDeserialize();
+}

+ 31 - 0
src/holeg/serialize/PostDeserializeEnabler.java

@@ -0,0 +1,31 @@
+package holeg.serialize;
+
+import com.google.gson.Gson;
+import com.google.gson.TypeAdapter;
+import com.google.gson.TypeAdapterFactory;
+import com.google.gson.reflect.TypeToken;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+
+import java.io.IOException;
+
+public class PostDeserializeEnabler implements TypeAdapterFactory {
+    @Override
+    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
+        final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
+
+        return new TypeAdapter<T>() {
+            public void write(JsonWriter out, T value) throws IOException {
+                delegate.write(out, value);
+            }
+
+            public T read(JsonReader in) throws IOException {
+                T obj = delegate.read(in);
+                if (obj instanceof PostDeserialize post) {
+                    post.postDeserialize();
+                }
+                return obj;
+            }
+        };
+    }
+}

+ 5 - 16
src/holeg/ui/controller/Control.java

@@ -1,9 +1,5 @@
 package holeg.ui.controller;
 
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import holeg.adapter.EdgeSerializer;
-import holeg.adapter.ModelDeserializer;
 import holeg.model.*;
 import holeg.preferences.ImagePreference;
 import holeg.ui.model.GuiSettings;
@@ -22,6 +18,8 @@ import java.io.IOException;
 import java.util.*;
 import java.util.logging.Logger;
 
+import static holeg.serialize.GsonCollection.Gson;
+
 /**
  * The Class represents the controller.
  */
@@ -436,8 +434,7 @@ public class Control {
         log.info("load" + file);
         try {
             FileReader reader = new FileReader(file);
-            Gson gson = initGson();
-            Model model = gson.fromJson(reader, Model.class);
+            Model model = Gson.fromJson(reader, Model.class);
             reader.close();
             this.model = model;
             calculateStateAndVisualForCurrentTimeStep();
@@ -453,8 +450,7 @@ public class Control {
         log.info("save" + file);
         try {
             FileWriter  writer = new FileWriter(file);
-            Gson gson = initGson();
-            gson.toJson(model, writer);
+            Gson.toJson(model, writer);
             writer.close();
         } catch (IOException e) {
             log.warning(e.getLocalizedMessage());
@@ -462,14 +458,7 @@ public class Control {
         GuiSettings.setActualSaveFile(file);
     }
 
-    public Gson initGson() {
-        GsonBuilder builder = new GsonBuilder();
-        builder.registerTypeAdapter(Edge.class, new EdgeSerializer());
-        builder.registerTypeAdapter(Model.class, new ModelDeserializer());
-        builder.serializeNulls();
-        builder.setPrettyPrinting();
-        return builder.create();
-    }
+
 
 
     public void clearModel() {

+ 0 - 5
src/holeg/ui/view/main/Gui.java

@@ -697,11 +697,6 @@ public class Gui {
 
         holegJFrame.getContentPane().add(timePanel, BorderLayout.SOUTH);
 
-//		try {
-//			control.loadAutoSave(System.getProperty("user.home") + "/.config/HolonGUI/Category/Category.json");
-//		} catch (IOException e1) {
-//		}
-
         canvasSP.addComponentListener(new ComponentAdapter() {
             @Override
             public void componentResized(ComponentEvent e) {