Quellcode durchsuchen

refactoring, resolving warnings

I. Dix vor 7 Jahren
Ursprung
Commit
f108f947fa

+ 428 - 474
src/ui/controller/ClipboardController.java

@@ -1,486 +1,440 @@
 package ui.controller;
 
-import java.awt.Point;
-import java.awt.Toolkit;
-import java.awt.datatransfer.Clipboard;
-import java.awt.datatransfer.DataFlavor;
-import java.awt.datatransfer.StringSelection;
-import java.awt.datatransfer.Transferable;
-import java.awt.datatransfer.UnsupportedFlavorException;
-import java.io.IOException;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.stream.Collectors;
-
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonPrimitive;
-
-import classes.AbstractCpsObject;
-import classes.CpsEdge;
-import classes.CpsUpperNode;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.IdCounter;
-import classes.IdCounterElem;
-import classes.Position;
+import classes.*;
+import com.google.gson.*;
 import ui.controller.SaveController.EDGETYPE;
 import ui.controller.SaveController.GRAPHTYPE;
 import ui.controller.SaveController.NUMTYPE;
 import ui.controller.SaveController.TYPE;
 import ui.model.Model;
 
+import java.awt.*;
+import java.awt.datatransfer.*;
+import java.io.IOException;
+import java.util.*;
+import java.util.List;
+import java.util.stream.Collectors;
+
 public class ClipboardController {
 
-	private Model model;
-	private SaveController store;
-	private LoadController load;
-	private CanvasController cvsC;
-	private ObjectController objC;
-	private NodeController uppC;
-	private JsonParser parser;
-	private Clipboard clipboard;
-	private HashMap<Integer, Integer> objIDMap;
-	private HashMap<Integer, Integer> eleIDMap;
-	private String sav;
-	private Point point;
-
-	public ClipboardController(Model model, SaveController store, LoadController load, CanvasController cvs,
-			ObjectController obj, NodeController uppC, MultiPurposeController mp) {
-		this.model = model;
-		this.store = store;
-		this.load = load;
-		this.cvsC = cvs;
-		this.objC = obj;
-		this.uppC = uppC;
-		this.clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
-		parser = new JsonParser();
-	}
-
-	/**
-	 * Copy marked Objects into Clipboard in Json Format
-	 * @param upperNode
-	 */
-	public void copy(CpsUpperNode upperNode) {
-
-		JsonObject file = new JsonObject();
-		ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
-		AbstractCpsObject u = null;
-
-		store.initNumeration();
-
-		file.add("SAV", new JsonPrimitive((upperNode == null ? "CVS" : "" + upperNode.getId())));
-		Position pos = uppC.calculatePos(model.getSelectedCpsObjects());
-		file.add("CENTER", model.getGson().toJsonTree(pos, Position.class));
-
-		for (AbstractCpsObject abs : model.getSelectedCpsObjects()) {
-			queue.add(abs);
-		}
-
-		while (!queue.isEmpty()) {
-
-			u = queue.pop();
-
-			String key = "CVSOBJECT" + store.getNumerator(NUMTYPE.OBJECT);
-			file.add(key, model.getGson().toJsonTree(u, AbstractCpsObject.class));
-			edgeToJson(EDGETYPE.CONNECTION, file, u.getId(), u.getConnections());
-
-			if (u instanceof HolonObject)
-				store.elementsToJson(TYPE.CANVAS, file, u);
-
-			if (u instanceof HolonSwitch)
-				if (((HolonSwitch) u).getGraphPoints().size() != 0)
-					store.unitgraphToJson(GRAPHTYPE.SWITCH, file, u.getId(), ((HolonSwitch) u).getGraphPoints());
-
-			if (u instanceof CpsUpperNode) {
-				for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
-					queue.add(adjacent);
-				}
-				edgeToJson(EDGETYPE.NODE, file, u.getId(), ((CpsUpperNode) u).getNodeEdges());
-				edgeToJson(EDGETYPE.OLD, file, u.getId(), ((CpsUpperNode) u).getOldEdges());
-			}
-		}
-		if (upperNode == null)
-			edgeToJson(EDGETYPE.LAYER, file, 0, model.getEdgesOnCanvas());
-		else
-			edgeToJson(EDGETYPE.LAYER, file, upperNode.getId(), upperNode.getNodeEdges());
-
-		StringSelection selection = new StringSelection(model.getGson().toJson(file));
-		clipboard.setContents(selection, selection);
-
-	}
-
-	/**
-	 * Paste the Copied JsonTree into Canvas
-	 * @param upperNode
-	 */
-	public void paste(CpsUpperNode upperNode, Point p)
-			throws UnsupportedFlavorException, IOException, JsonParseException {
-
-		if (p == null)
-			return;
-
-		JsonObject json = new JsonObject();
-		Transferable content = clipboard.getContents(null);
-
-		if (content != null && content.isDataFlavorSupported(DataFlavor.stringFlavor)
-				&& !content.isDataFlavorSupported(DataFlavor.allHtmlFlavor)) {
-
-			String str = (String) content.getTransferData(DataFlavor.stringFlavor);
-
-			if (parser.parse(str).isJsonObject())
-				json = (JsonObject) parser.parse(str);
-			else
-				throw new JsonParseException("Unknown Clipboard Information");
-
-		} else
-			return;
-
-		List<String> keys = load.getKeys(json);
-		List<String> edges = keys.stream().filter(key -> key.contains("EDGE"))
-				.collect(Collectors.toCollection(ArrayList::new));
-
-		HashMap<Integer, AbstractCpsObject> objDispatch = new HashMap<>();
-		HashMap<Integer, HolonElement> eleDispatch = new HashMap<>();
-		model.getSelectedCpsObjects().clear();
-
-		objIDMap = new HashMap<>();
-		eleIDMap = new HashMap<>();
-		sav = json.get("SAV").getAsString();
-
-		Position old = model.getGson().getAdapter(Position.class).fromJsonTree(json.get("CENTER"));
-		point = new Point(old.x - p.x, old.y - p.y);
-
-		forwardObjects(keys, json, objDispatch, eleDispatch, upperNode);
-		// for selecting Cps
-		getObjectsInDepth();
-		forwardEdges(edges, json, objDispatch, upperNode);
-
-	}
-	
-	/**
-	 * Cuts the marked Objects out of Canvas and saves them into the Clipboard
-	 * @param upperNode
-	 */
-	public void cut(CpsUpperNode upperNode) {
-		copy(upperNode);
-		for (AbstractCpsObject abs : model.getSelectedCpsObjects()) {
-			if (upperNode == null)
-				cvsC.deleteObjectOnCanvas(abs);
-			else
-				uppC.deleteObjectInUpperNode(abs, upperNode);
-
-			if (abs instanceof CpsUpperNode)
-				cvsC.bfsNodeCleaner((CpsUpperNode) abs);
-		}
-
-	}
-
-	private void forwardEdges(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
-			CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
-		List<String> conn = new ArrayList<>();
-
-		for (String edge : keys) {
-			if (edge.contains("LAYEREDGE"))
-				loadEdge(EDGETYPE.LAYER, json.get(edge), objDispatch, upperNode);
-			if (edge.contains("CONNEDGE"))
-				conn.add(edge);
-			if (edge.contains("NODEEDGE"))
-				loadEdge(EDGETYPE.NODE, json.get(edge), objDispatch, null);
-			if (edge.contains("OLDEDGE"))
-				loadEdge(EDGETYPE.OLD, json.get(edge), objDispatch, null);
-		}
-
-		for (String edge : conn) {
-			loadEdge(EDGETYPE.CONNECTION, json.get(edge), objDispatch, null);
-		}
-
-	}
-
-	private void forwardObjects(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
-			HashMap<Integer, HolonElement> eleDispatch, CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
-
-		for (String key : keys) {
-			if (key.contains("CVSOBJECT"))
-				loadCanvasObject(json.get(key), objDispatch, upperNode);
-			if (key.contains("CVSELEMENT"))
-				loadCanvasElements(json.get(key), objDispatch, eleDispatch);
-			if (key.contains("SWUNITGRAPH"))
-				loadUnitGraph(GRAPHTYPE.SWITCH, json.get(key), objDispatch, null);
-			if (key.contains("ELEUNITGRAPH"))
-				loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
-		}
-	}
-
-	private void loadCanvasObject(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
-			CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
-		AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
-		load.initObjects(temp);
-		objIDMapper(temp);
-		updatePosition(temp, upperNode);
-
-		// if its stored before on the canvas just put it there
-		if (temp.getSav().equals(sav)) {
-			if (upperNode == null)
-				cvsC.addObject(temp);
-			else
-				uppC.addObjectInUpperNode(temp, upperNode);
-			// mark the Pasted Objects
-			model.getSelectedCpsObjects().add(temp);
-		} else {
-			// else look up the table and put it into the right Uppernode
-			CpsUpperNode temp2 = (CpsUpperNode) objDispatch.get(objIDMap.get(Integer.parseInt(temp.getSav())));
-			uppC.addObjectInUpperNode(temp, temp2);
-		}
-
-		objDispatch.put(temp.getId(), temp);
-	}
-
-	private void loadCanvasElements(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
-			HashMap<Integer, HolonElement> eleDispatch) {
-		// TODO Auto-generated method stub
-		JsonObject object = jsonElement.getAsJsonObject();
-
-		HolonElement temp = model.getGson().fromJson(object.get("properties"), HolonElement.class);
-		load.initElements(temp);
-		eleIDMapper(temp);
-		// id which Object it was stored before
-		int stored = objIDMap.get(object.get("ID").getAsInt());
-		// lookup that object
-		HolonObject temp2 = (HolonObject) objDispatch.get(stored);
-		// add it
-		objC.addElement(temp2, temp);
-		// store element also inside a table
-		eleDispatch.put(temp.getId(), temp);
-
-	}
-
-	private void loadUnitGraph(GRAPHTYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
-			HashMap<Integer, HolonElement> eleDispatch) {
-		// TODO Auto-generated method stub
-		JsonObject object = jsonElement.getAsJsonObject();
-		List<String> keys = load.getKeys(object);
-		String p = null;
-		int mid, x, y = 0;
-
-		LinkedList<Point> graphpoint = new LinkedList<>();
-		int sav = 0;
-		// foreach Point in the graph restore it
-		for (String k : keys) {
-			if (!k.equals("ID")) {
-				p = object.get(k).getAsString();
-				mid = p.indexOf(':');
-				x = Integer.parseInt(p.substring(0, mid));
-				y = Integer.parseInt(p.substring(mid + 1, p.length()));
-				graphpoint.add(new Point(x, y));
-			} else
-				// else its an ID
-				sav = object.get(k).getAsInt();
-
-		}
-
-		switch (type) {
-		case SWITCH:
-			sav = objIDMap.get(sav);
-			HolonSwitch sw = (HolonSwitch) objDispatch.get(sav);
-			sw.setGraphPoints(graphpoint);
-			break;
-		case ELEMENT:
-			sav = eleIDMap.get(sav);
-			HolonElement ele = eleDispatch.get(sav);
-			ele.setGraphPoints(graphpoint);
-			break;
-		default:
-			break;
-		}
-
-	}
-	
-	/**
-	 * 
-	 * @param type
-	 * @param jsonElement
-	 * @param objDispatch
-	 * @param upperNode
-	 */
-	private void loadEdge(EDGETYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
-			CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
-		JsonObject object = jsonElement.getAsJsonObject();
-		CpsEdge temp = model.getGson().fromJson(object.get("properties"), CpsEdge.class);
-		load.initCpsEdge(temp);
-		// look for A and B inside the Table
-		temp.setA(objDispatch.get(objIDMap.get(object.get("A").getAsInt())));
-		temp.setB(objDispatch.get(objIDMap.get(object.get("B").getAsInt())));
-
-		int sav = 0;
-
-		switch (type) {
-		case LAYER:
-			// if in canvas add it into the canvas but delete connection before
-			(upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges()).add(temp);
-			break;
-		case CONNECTION:
-			// if no duplicates in connection store them into the given A and B
-			if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getA().getConnections()))
-				temp.getA().getConnections().add(temp);
-			if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getB().getConnections()))
-				temp.getB().getConnections().add(temp);
-			break;
-		case NODE:
-			// put it into given nodeofnode
-			sav = objIDMap.get(object.get("ID").getAsInt());
-			((CpsUpperNode) objDispatch.get(sav)).getNodeEdges().add(temp);
-			break;
-		case OLD:
-			// same as above
-			sav = objIDMap.get(object.get("ID").getAsInt());
-			((CpsUpperNode) objDispatch.get(sav)).getOldEdges().add(temp);
-			break;
-		default:
-			break;
-		}
-
-		if (object.get("connection").getAsBoolean() && !type.equals(EDGETYPE.CONNECTION)) {
-			temp.getA().getConnections().add(temp);
-			temp.getB().getConnections().add(temp);
-		}
-
-	}
-
-	/**
-	 * Modified Method from LoadController. Slightly different
-	 * @param type
-	 * @param file
-	 * @param id
-	 * @param arr
-	 */
-	private void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
-		// TODO Auto-generated method stub
-		String k = null;
-		boolean b = false;
-		JsonObject temp = new JsonObject();
-
-		for (CpsEdge edge : arr) {
-			if (model.getClipboradObjects().contains(edge.getA())
-					&& model.getClipboradObjects().contains(edge.getB())) {
-				// add properties and only the ids from a and b
-				temp.add("properties", model.getGson().toJsonTree(edge));
-				temp.add("A", new JsonPrimitive(edge.getA().getId()));
-				temp.add("B", new JsonPrimitive(edge.getB().getId()));
-
-				// Key and occasionally the id of Uppernode
-				switch (type) {
-				case LAYER:
-					temp.add("ID", new JsonPrimitive(id));
-					k = "LAYEREDGE" + store.getNumerator(NUMTYPE.EDGE);
-					break;
-				case CONNECTION:
-					k = "CONNEDGE" + store.getNumerator(NUMTYPE.CONNECTION);
-					break;
-				case NODE:
-					temp.add("ID", new JsonPrimitive(id));
-					k = "NODEEDGE" + store.getNumerator(NUMTYPE.NODEEDGE);
-					break;
-				case OLD:
-					temp.add("ID", new JsonPrimitive(id));
-					k = "OLDEDGE" + store.getNumerator(NUMTYPE.OLDEDGE);
-					break;
-				default:
-					break;
-				}
-				// lookup if the CVS, NODE or OLDEDGE are also connections
-				if (edge.getA().getConnections().contains(edge) && edge.getA().getConnections().contains(edge)
-						&& !type.equals(EDGETYPE.CONNECTION))
-					b = true;
-				temp.add("connection", new JsonPrimitive(b));
-				file.add(k, model.getGson().toJsonTree(temp));
-				temp = new JsonObject();
-			}
-		}
-	}
-
-	/**
-	 * Adds all Objects in Depth into Clipboardobjects preemptive when objects are selected
-	 */
-	public void getObjectsInDepth() {
-		model.setClipboradObjects(new ArrayList<>());
-		for (AbstractCpsObject obj : model.getSelectedCpsObjects()) {
-			clipboadDepth(obj);
-		}
-	}
-
-	/**
-	 * Get all Objects inside the Currentobject and add them into ClipboardObjects
-	 * @param obj
-	 */
-	private void clipboadDepth(AbstractCpsObject obj) {
-		//modified backtracking Algorithm no True/False
-		if (!(obj instanceof CpsUpperNode)) {
-			model.getClipboradObjects().add(obj);
-			return;
-		} else {
-			model.getClipboradObjects().add(obj);
-			for (AbstractCpsObject abs : ((CpsUpperNode) obj).getNodes()) {
-				clipboadDepth(abs);
-			}
-			return;
-		}
-
-	}
-	
-	/**
-	 * Map the Copied Object ID into a new One
-	 * @param temp
-	 */
-	private void objIDMapper(AbstractCpsObject temp) {
-		// TODO Auto-generated method stub
-		int id = temp.getId();
-		temp.setId(IdCounter.nextId());
-		// oldID -> currentID
-		objIDMap.put(id, temp.getId());
-	}
-	/**
-	 * Map the Copied Element ID into a new One
-	 * @param temp
-	 */
-	private void eleIDMapper(HolonElement temp) {
-		// TODO Auto-generated method stub
-		int id = temp.getId();
-		temp.setId(IdCounterElem.nextId());
-		// oldID -> currentID
-		eleIDMap.put(id, temp.getId());
-
-	}
-
-	private void updatePosition(AbstractCpsObject temp, CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
-		int x = temp.getPosition().x - point.x;
-		int y = temp.getPosition().y - point.y;
-
-		if (y < 0)
-			y = 0 + model.getScaleDiv2() + 1;
-		if (upperNode != null) {
-			if (x < upperNode.getLeftBorder() + model.getScaleDiv2() + 1)
-				x = upperNode.getLeftBorder() + model.getScaleDiv2() + 1;
-		} else if (x < 0)
-			x = 0 + model.getScaleDiv2() + 1;
-		if (x > model.getCanvasX())
-			x = model.getCanvasX() - model.getScaleDiv2() - 1;
-		if (y > model.getCanvasX())
-			y = model.getCanvasY() - model.getScaleDiv2() - 1;
-
-		temp.setPosition(new Position(x, y));
-
-	}
+    private Model model;
+    private SaveController store;
+    private LoadController load;
+    private CanvasController cvsC;
+    private ObjectController objC;
+    private NodeController uppC;
+    private JsonParser parser;
+    private Clipboard clipboard;
+    private HashMap<Integer, Integer> objIDMap;
+    private HashMap<Integer, Integer> eleIDMap;
+    private String sav;
+    private Point point;
+
+    ClipboardController(Model model, SaveController store, LoadController load, CanvasController cvs,
+                        ObjectController obj, NodeController uppC, MultiPurposeController mp) {
+        this.model = model;
+        this.store = store;
+        this.load = load;
+        this.cvsC = cvs;
+        this.objC = obj;
+        this.uppC = uppC;
+        this.clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
+        parser = new JsonParser();
+    }
+
+    /**
+     * Copy marked Objects into Clipboard in Json Format
+     */
+    public void copy(CpsUpperNode upperNode) {
+
+        JsonObject file = new JsonObject();
+        ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
+        AbstractCpsObject u = null;
+
+        store.initNumeration();
+
+        file.add("SAV", new JsonPrimitive((upperNode == null ? "CVS" : "" + upperNode.getId())));
+        Position pos = uppC.calculatePos(model.getSelectedCpsObjects());
+        file.add("CENTER", model.getGson().toJsonTree(pos, Position.class));
+
+        for (AbstractCpsObject abs : model.getSelectedCpsObjects()) {
+            queue.add(abs);
+        }
+
+        while (!queue.isEmpty()) {
+
+            u = queue.pop();
+
+            String key = "CVSOBJECT" + store.getNumerator(NUMTYPE.OBJECT);
+            file.add(key, model.getGson().toJsonTree(u, AbstractCpsObject.class));
+            edgeToJson(EDGETYPE.CONNECTION, file, u.getId(), u.getConnections());
+
+            if (u instanceof HolonObject)
+                store.elementsToJson(TYPE.CANVAS, file, u);
+
+            if (u instanceof HolonSwitch)
+                if (((HolonSwitch) u).getGraphPoints().size() != 0)
+                    store.unitgraphToJson(GRAPHTYPE.SWITCH, file, u.getId(), ((HolonSwitch) u).getGraphPoints());
+
+            if (u instanceof CpsUpperNode) {
+                for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
+                    queue.add(adjacent);
+                }
+                edgeToJson(EDGETYPE.NODE, file, u.getId(), ((CpsUpperNode) u).getNodeEdges());
+                edgeToJson(EDGETYPE.OLD, file, u.getId(), ((CpsUpperNode) u).getOldEdges());
+            }
+        }
+        if (upperNode == null)
+            edgeToJson(EDGETYPE.LAYER, file, 0, model.getEdgesOnCanvas());
+        else
+            edgeToJson(EDGETYPE.LAYER, file, upperNode.getId(), upperNode.getNodeEdges());
+
+        StringSelection selection = new StringSelection(model.getGson().toJson(file));
+        clipboard.setContents(selection, selection);
+
+    }
+
+    /**
+     * Paste the Copied JsonTree into Canvas
+     */
+    void paste(CpsUpperNode upperNode, Point p)
+            throws UnsupportedFlavorException, IOException, JsonParseException {
+
+        if (p == null)
+            return;
+
+        JsonObject json;
+        Transferable content = clipboard.getContents(null);
+
+        if (content != null && content.isDataFlavorSupported(DataFlavor.stringFlavor)
+                && !content.isDataFlavorSupported(DataFlavor.allHtmlFlavor)) {
+
+            String str = (String) content.getTransferData(DataFlavor.stringFlavor);
+
+            if (parser.parse(str).isJsonObject())
+                json = (JsonObject) parser.parse(str);
+            else
+                throw new JsonParseException("Unknown Clipboard Information");
+
+        } else
+            return;
+
+        List<String> keys = load.getKeys(json);
+        List<String> edges = keys.stream().filter(key -> key.contains("EDGE"))
+                .collect(Collectors.toCollection(ArrayList::new));
+
+        HashMap<Integer, AbstractCpsObject> objDispatch = new HashMap<>();
+        HashMap<Integer, HolonElement> eleDispatch = new HashMap<>();
+        model.getSelectedCpsObjects().clear();
+
+        objIDMap = new HashMap<>();
+        eleIDMap = new HashMap<>();
+        sav = json.get("SAV").getAsString();
+
+        Position old = model.getGson().getAdapter(Position.class).fromJsonTree(json.get("CENTER"));
+        point = new Point(old.x - p.x, old.y - p.y);
+
+        forwardObjects(keys, json, objDispatch, eleDispatch, upperNode);
+        // for selecting Cps
+        getObjectsInDepth();
+        forwardEdges(edges, json, objDispatch, upperNode);
+
+    }
+
+    /**
+     * Cuts the marked Objects out of Canvas and saves them into the Clipboard
+     */
+    void cut(CpsUpperNode upperNode) {
+        copy(upperNode);
+        for (AbstractCpsObject abs : model.getSelectedCpsObjects()) {
+            if (upperNode == null)
+                cvsC.deleteObjectOnCanvas(abs);
+            else
+                uppC.deleteObjectInUpperNode(abs, upperNode);
+
+            if (abs instanceof CpsUpperNode)
+                cvsC.bfsNodeCleaner((CpsUpperNode) abs);
+        }
+
+    }
+
+    private void forwardEdges(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
+                              CpsUpperNode upperNode) {
+        List<String> conn = new ArrayList<>();
+
+        for (String edge : keys) {
+            if (edge.contains("LAYEREDGE"))
+                loadEdge(EDGETYPE.LAYER, json.get(edge), objDispatch, upperNode);
+            if (edge.contains("CONNEDGE"))
+                conn.add(edge);
+            if (edge.contains("NODEEDGE"))
+                loadEdge(EDGETYPE.NODE, json.get(edge), objDispatch, null);
+            if (edge.contains("OLDEDGE"))
+                loadEdge(EDGETYPE.OLD, json.get(edge), objDispatch, null);
+        }
+
+        for (String edge : conn) {
+            loadEdge(EDGETYPE.CONNECTION, json.get(edge), objDispatch, null);
+        }
+
+    }
+
+    private void forwardObjects(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
+                                HashMap<Integer, HolonElement> eleDispatch, CpsUpperNode upperNode) {
+
+        for (String key : keys) {
+            if (key.contains("CVSOBJECT"))
+                loadCanvasObject(json.get(key), objDispatch, upperNode);
+            if (key.contains("CVSELEMENT"))
+                loadCanvasElements(json.get(key), objDispatch, eleDispatch);
+            if (key.contains("SWUNITGRAPH"))
+                loadUnitGraph(GRAPHTYPE.SWITCH, json.get(key), objDispatch, null);
+            if (key.contains("ELEUNITGRAPH"))
+                loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
+        }
+    }
+
+    private void loadCanvasObject(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
+                                  CpsUpperNode upperNode) {
+        AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
+        load.initObjects(temp);
+        objIDMapper(temp);
+        updatePosition(temp, upperNode);
+
+        // if its stored before on the canvas just put it there
+        if (temp.getSav().equals(sav)) {
+            if (upperNode == null)
+                cvsC.addObject(temp);
+            else
+                uppC.addObjectInUpperNode(temp, upperNode);
+            // mark the Pasted Objects
+            model.getSelectedCpsObjects().add(temp);
+        } else {
+            // else look up the table and put it into the right Uppernode
+            CpsUpperNode temp2 = (CpsUpperNode) objDispatch.get(objIDMap.get(Integer.parseInt(temp.getSav())));
+            uppC.addObjectInUpperNode(temp, temp2);
+        }
+
+        objDispatch.put(temp.getId(), temp);
+    }
+
+    private void loadCanvasElements(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
+                                    HashMap<Integer, HolonElement> eleDispatch) {
+        JsonObject object = jsonElement.getAsJsonObject();
+
+        HolonElement temp = model.getGson().fromJson(object.get("properties"), HolonElement.class);
+        load.initElements(temp);
+        eleIDMapper(temp);
+        // id which Object it was stored before
+        int stored = objIDMap.get(object.get("ID").getAsInt());
+        // lookup that object
+        HolonObject temp2 = (HolonObject) objDispatch.get(stored);
+        // add it
+        objC.addElement(temp2, temp);
+        // store element also inside a table
+        eleDispatch.put(temp.getId(), temp);
+
+    }
+
+    private void loadUnitGraph(GRAPHTYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
+                               HashMap<Integer, HolonElement> eleDispatch) {
+        JsonObject object = jsonElement.getAsJsonObject();
+        List<String> keys = load.getKeys(object);
+        String p;
+        int mid, x, y;
+
+        LinkedList<Point> graphpoint = new LinkedList<>();
+        int sav = 0;
+        // foreach Point in the graph restore it
+        for (String k : keys) {
+            if (!k.equals("ID")) {
+                p = object.get(k).getAsString();
+                mid = p.indexOf(':');
+                x = Integer.parseInt(p.substring(0, mid));
+                y = Integer.parseInt(p.substring(mid + 1, p.length()));
+                graphpoint.add(new Point(x, y));
+            } else
+                // else its an ID
+                sav = object.get(k).getAsInt();
+
+        }
+
+        switch (type) {
+            case SWITCH:
+                sav = objIDMap.get(sav);
+                HolonSwitch sw = (HolonSwitch) objDispatch.get(sav);
+                sw.setGraphPoints(graphpoint);
+                break;
+            case ELEMENT:
+                sav = eleIDMap.get(sav);
+                HolonElement ele = eleDispatch.get(sav);
+                ele.setGraphPoints(graphpoint);
+                break;
+            default:
+                break;
+        }
+
+    }
+
+    /**
+     * loads an edge from json
+     */
+    private void loadEdge(EDGETYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
+                          CpsUpperNode upperNode) {
+        JsonObject object = jsonElement.getAsJsonObject();
+        CpsEdge temp = model.getGson().fromJson(object.get("properties"), CpsEdge.class);
+        load.initCpsEdge(temp);
+        // look for A and B inside the Table
+        temp.setA(objDispatch.get(objIDMap.get(object.get("A").getAsInt())));
+        temp.setB(objDispatch.get(objIDMap.get(object.get("B").getAsInt())));
+
+        int sav;
+
+        switch (type) {
+            case LAYER:
+                // if in canvas add it into the canvas but delete connection before
+                (upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges()).add(temp);
+                break;
+            case CONNECTION:
+                // if no duplicates in connection store them into the given A and B
+                if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getA().getConnections()))
+                    temp.getA().getConnections().add(temp);
+                if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getB().getConnections()))
+                    temp.getB().getConnections().add(temp);
+                break;
+            case NODE:
+                // put it into given nodeofnode
+                sav = objIDMap.get(object.get("ID").getAsInt());
+                ((CpsUpperNode) objDispatch.get(sav)).getNodeEdges().add(temp);
+                break;
+            case OLD:
+                // same as above
+                sav = objIDMap.get(object.get("ID").getAsInt());
+                ((CpsUpperNode) objDispatch.get(sav)).getOldEdges().add(temp);
+                break;
+            default:
+                break;
+        }
+
+        if (object.get("connection").getAsBoolean() && !type.equals(EDGETYPE.CONNECTION)) {
+            temp.getA().getConnections().add(temp);
+            temp.getB().getConnections().add(temp);
+        }
+
+    }
+
+    /**
+     * Modified Method from LoadController. Slightly different
+     */
+    private void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
+        String k = null;
+        boolean b = false;
+        JsonObject temp = new JsonObject();
+
+        for (CpsEdge edge : arr) {
+            if (model.getClipboradObjects().contains(edge.getA())
+                    && model.getClipboradObjects().contains(edge.getB())) {
+                // add properties and only the ids from a and b
+                temp.add("properties", model.getGson().toJsonTree(edge));
+                temp.add("A", new JsonPrimitive(edge.getA().getId()));
+                temp.add("B", new JsonPrimitive(edge.getB().getId()));
+
+                // Key and occasionally the id of Uppernode
+                switch (type) {
+                    case LAYER:
+                        temp.add("ID", new JsonPrimitive(id));
+                        k = "LAYEREDGE" + store.getNumerator(NUMTYPE.EDGE);
+                        break;
+                    case CONNECTION:
+                        k = "CONNEDGE" + store.getNumerator(NUMTYPE.CONNECTION);
+                        break;
+                    case NODE:
+                        temp.add("ID", new JsonPrimitive(id));
+                        k = "NODEEDGE" + store.getNumerator(NUMTYPE.NODEEDGE);
+                        break;
+                    case OLD:
+                        temp.add("ID", new JsonPrimitive(id));
+                        k = "OLDEDGE" + store.getNumerator(NUMTYPE.OLDEDGE);
+                        break;
+                    default:
+                        break;
+                }
+                // lookup if the CVS, NODE or OLDEDGE are also connections
+                if (edge.getA().getConnections().contains(edge) && edge.getA().getConnections().contains(edge)
+                        && !type.equals(EDGETYPE.CONNECTION))
+                    b = true;
+                temp.add("connection", new JsonPrimitive(b));
+                file.add(k, model.getGson().toJsonTree(temp));
+                temp = new JsonObject();
+            }
+        }
+    }
+
+    /**
+     * Adds all Objects in Depth into Clipboardobjects preemptive when objects are selected
+     */
+    void getObjectsInDepth() {
+        model.setClipboradObjects(new ArrayList<>());
+        for (AbstractCpsObject obj : model.getSelectedCpsObjects()) {
+            clipboadDepth(obj);
+        }
+    }
+
+    /**
+     * Get all Objects inside the Currentobject and add them into ClipboardObjects
+     */
+    private void clipboadDepth(AbstractCpsObject obj) {
+        //modified backtracking Algorithm no True/False
+        if (!(obj instanceof CpsUpperNode)) {
+            model.getClipboradObjects().add(obj);
+        } else {
+            model.getClipboradObjects().add(obj);
+            for (AbstractCpsObject abs : ((CpsUpperNode) obj).getNodes()) {
+                clipboadDepth(abs);
+            }
+        }
+
+    }
+
+    /**
+     * Map the Copied Object ID into a new One
+     */
+    private void objIDMapper(AbstractCpsObject temp) {
+        int id = temp.getId();
+        temp.setId(IdCounter.nextId());
+        // oldID -> currentID
+        objIDMap.put(id, temp.getId());
+    }
+
+    /**
+     * Map the Copied Element ID into a new One
+     */
+    private void eleIDMapper(HolonElement temp) {
+        int id = temp.getId();
+        temp.setId(IdCounterElem.nextId());
+        // oldID -> currentID
+        eleIDMap.put(id, temp.getId());
+
+    }
+
+    private void updatePosition(AbstractCpsObject temp, CpsUpperNode upperNode) {
+        int x = temp.getPosition().x - point.x;
+        int y = temp.getPosition().y - point.y;
+
+        if (y < 0)
+            y = 0 + model.getScaleDiv2() + 1;
+        if (upperNode != null) {
+            if (x < upperNode.getLeftBorder() + model.getScaleDiv2() + 1)
+                x = upperNode.getLeftBorder() + model.getScaleDiv2() + 1;
+        } else if (x < 0)
+            x = 0 + model.getScaleDiv2() + 1;
+        if (x > model.getCanvasX())
+            x = model.getCanvasX() - model.getScaleDiv2() - 1;
+        if (y > model.getCanvasX())
+            y = model.getCanvasY() - model.getScaleDiv2() - 1;
+
+        temp.setPosition(new Position(x, y));
+
+    }
 
 }

+ 489 - 549
src/ui/controller/LoadController.java

@@ -20,560 +20,500 @@ import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.stream.Collectors;
-import java.util.zip.ZipException;
 
 /**
  * Controller for the Loading.
- * 
+ *
  * @author Gruppe14
  */
 public class LoadController {
-	private Model model;
-	private CategoryController cgC;
-	private CanvasController cvsC;
-	private ObjectController objC;
-	private NodeController uppC;
-	private MultiPurposeController mpC;
-	private JsonParser parser;
-	/**
-	 * Constructor.
-	 *
-	 * @param model
-	 *            Model
-	 * @param cg
-	 *            CategoryController
-	 * @param cvs
-	 *            CanvasController
-	 * @param obj
-	 *            ObjectController
-	 * @param mp
-	 *            MultiPurposeController
-	 */
-	public LoadController(Model model, CategoryController cg, CanvasController cvs, ObjectController obj,
-			NodeController uppC, MultiPurposeController mp) {
-		this.model = model;
-		this.cgC = cg;
-		this.cvsC = cvs;
-		this.objC = obj;
-		this.uppC = uppC;
-		this.mpC = mp;
-		this.parser = new JsonParser();
-	}
-
-	/**
-	 * Reads the the JSON File and load the state into the Model.
-	 *
-	 * @param path
-	 *            the Path
-	 * @throws IOException
-	 *             exception
-	 */
-	public void readSave(String path) throws IOException, ArchiveException, ZipException {
-
-		File src = new File(path);
-		File folder = readArchive(path, src);
-		folder.deleteOnExit();
-		String trim = folder.getPath().substring(0,
-				folder.getPath().lastIndexOf(folder.getName()) + folder.getName().length());
-
-		forwardFiles(folder, trim);
-
-	}
-
-	public void readJson(String path) throws IOException {
-		JsonObject json = (JsonObject) parser.parse(new FileReader(path));
-		// get all keys via stream
-		List<String> keys = getKeys(json);
-		List<String> edges = keys.stream().filter(key -> key.contains("EDGE"))
-				.collect(Collectors.toCollection(ArrayList::new));
-
-		HashMap<Integer, AbstractCpsObject> objDispatch = new HashMap<>();
-		HashMap<Integer, HolonElement> eleDispatch = new HashMap<>();
-
-		initialize(keys, json);
-		forwardObjects(keys, json, objDispatch, eleDispatch);
-		forwardEdges(edges, json, objDispatch);
-
-	}
-
-	/**
-	 * Loads the Files from the Savefile
-	 *
-	 * @param folder
-	 * @param trim
-	 * @throws IOException
-	 */
-	private void forwardFiles(File folder, String trim) throws IOException {
-		// TODO Auto-generated method stub
-		for (File file : folder.listFiles()) {
-			File dst = new File(
-					System.getProperty("user.home") + "/.config/HolonGUI/" + file.getPath().replace(trim, ""));
-
-			if (file.getName().contains(".json"))
-				readJson(file.getPath());
-			else if (file.isDirectory())
-				forwardFiles(file, trim);
-			else {
-				dst.getParentFile().mkdirs();
-				Files.copy(file.toPath(), dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
-			}
-
-		}
-	}
-
-	/**
-	 * distribute the Edges
-	 *
-	 * @param edges
-	 * @param json
-	 * @param objDispatch
-	 */
-	private void forwardEdges(List<String> edges, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch) {
-		// TODO Auto-generated method stub
-
-		List<String> conn = new ArrayList<>();
-
-		for (String edge : edges) {
-			if (edge.contains("CVSEDGE"))
-				loadEdge(EDGETYPE.CANVAS, json.get(edge), objDispatch);
-			if (edge.contains("CONNEDGE"))
-				conn.add(edge);
-			if (edge.contains("NODE"))
-				loadEdge(EDGETYPE.NODE, json.get(edge), objDispatch);
-			if (edge.contains("OLD"))
-				loadEdge(EDGETYPE.OLD, json.get(edge), objDispatch);
-		}
-
-		for (String edge : conn) {
-			loadEdge(EDGETYPE.CONNECTION, json.get(edge), objDispatch);
-		}
-
-	}
-
-	/**
-	 * Distribute the given keys for right processing
-	 *
-	 * @param keys
-	 * @param json
-	 * @param objDispatch
-	 * @param eleDispatch
-	 */
-	private void forwardObjects(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
-			HashMap<Integer, HolonElement> eleDispatch) {
-		// TODO Auto-generated method stub
-		for (String key : keys) {
-			if (key.contains("CATEGORY"))
-				loadCategory(json.get(key));
-			if (key.contains("CGOBJECT"))
-				loadCategoryObject(json.get(key));
-			if (key.contains("CGELEMENT"))
-				loadCategoryElements(json.get(key));
-			if (key.contains("CVSOBJECT"))
-				loadCanvasObject(json.get(key), objDispatch);
-			if (key.contains("CVSELEMENT"))
-				loadCanvasElements(json.get(key), objDispatch, eleDispatch);
-			if (key.contains("SWUNITGRAPH"))
-				loadUnitGraph(GRAPHTYPE.SWITCH, json.get(key), objDispatch, null);
-			if (key.contains("ELEUNITGRAPH"))
-				loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
-			if (key.contains("TRACKED"))
-				loadTracked(json.get(key), objDispatch);
-			if (key.contains("STATSGRAPH"))
-				loadStatisticGraph(json.get(key), objDispatch);
-		}
-
-	}
-
-	/**
-	 * Init the Global Parameters
-	 *
-	 * @param keys
-	 * @param json
-	 */
-	private void initialize(List<String> keys, JsonObject json) {
-
-		switch (MODE.valueOf(json.get("MODE").getAsString())) {
-		case COMPLETE:
-			model.setCvsObjIdx(new HashMap<Integer, Integer>());
-			model.setObjectsOnCanvas(new ArrayList<AbstractCpsObject>());
-			model.setEdgesOnCanvas(new ArrayList<CpsEdge>());
-			model.setTrackingObj(new ArrayList<>());
-			model.setStatisticData(new ArrayList<>());
-			model.setHashcodeMap(new HashMap<>());
-			model.setCanvasX(json.get("CANVAS_SIZE_X").getAsInt());
-			model.setCanvasX(json.get("CANVAS_SIZE_Y").getAsInt());
-			IdCounter.setCounter(json.get("IDCOUNTER").getAsInt());
-			IdCounterElem.setCounter(json.get("IDCOUNTERELEMENT").getAsInt());
-			break;
-		case PARTIAL:
-			model.setCvsObjIdx(new HashMap<Integer, Integer>());
-			model.setObjectsOnCanvas(new ArrayList<AbstractCpsObject>());
-			model.setEdgesOnCanvas(new ArrayList<CpsEdge>());
-			model.setHashcodeMap(new HashMap<>());
-			model.setCanvasX(json.get("CANVAS_SIZE_X").getAsInt());
-			model.setCanvasX(json.get("CANVAS_SIZE_Y").getAsInt());
-			IdCounter.setCounter(json.get("IDCOUNTER").getAsInt());
-			IdCounterElem.setCounter(json.get("IDCOUNTERELEMENT").getAsInt());
-			break;
-		case CATEGORY:
-			model.setCgIdx(new HashMap<String, Integer>());
-			model.setCategories(new ArrayList<Category>());
-
-		default:
-			break;
-		}
-
-	}
-
-	/**
-	 * Load a given Category
-	 *
-	 * @param jsonElement
-	 */
-	private void loadCategory(JsonElement jsonElement) {
-		// TODO Auto-generated method stub
-		if (mpC.searchCat(jsonElement.getAsString()) == null)
-			cgC.addCategory(new Category(jsonElement.getAsString()));
-	}
-
-	/**
-	 * Load a given Object in Category by Deserialization
-	 *
-	 * @param jsonElement
-	 */
-	private void loadCategoryObject(JsonElement jsonElement) {
-		// TODO Auto-generated method stub
-
-		AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
-		temp.setImage(checkOS(temp.getImage()));
-		initObjects(temp);
-		if (mpC.searchCatObj(mpC.searchCat(temp.getSav()), temp.getObjName()) != null)
-			cgC.deleteObject(temp.getSav(), temp.getObjName());
-		cgC.addObject(mpC.searchCat(temp.getSav()), temp);
-
-	}
-
-	/**
-	 * Load a given Element in Category by Deserialization
-	 *
-	 * @param jsonElement
-	 */
-	private void loadCategoryElements(JsonElement jsonElement) {
-		// TODO Auto-generated method stub
-		HolonElement temp = model.getGson().fromJson(jsonElement.getAsJsonObject().get("properties").getAsJsonObject(),
-				HolonElement.class);
-		initElements(temp);
-		objC.addElementIntoCategoryObject(temp.getSaving().getKey(), temp.getSaving().getValue(), temp);
-	}
-
-	/**
-	 * Load a given Object in Canvas by Deserialization
-	 *
-	 * @param jsonElement
-	 * @param objDispatch
-	 */
-	private void loadCanvasObject(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
-		// TODO Auto-generated method stub
-		AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
-		initObjects(temp);
-		temp.setImage(checkOS(temp.getImage()));
-		if (temp instanceof CpsUpperNode) {
-			model.getHashcodeMap().put(jsonElement.getAsJsonObject().get("hash").getAsInt(), (CpsUpperNode) temp);
-			((CpsUpperNode) temp).setLeftBorder(jsonElement.getAsJsonObject().get("properties").getAsJsonObject().get("leftBorder").getAsInt());
-		}
-		// if its stored before on the canvas just put it there
-		if (temp.getSav().equals("CVS")) {
-			cvsC.addObject(temp);
-
-		} else {
-			// else look up the table and put it into the right Uppernode
-			CpsUpperNode temp2 = (CpsUpperNode) objDispatch.get(Integer.parseInt(temp.getSav()));
-			uppC.addObjectInUpperNode(temp, temp2);
-		}
-
-		objDispatch.put(temp.getId(), temp);
-
-	}
-
-	/**
-	 * Load a given Element in Canvas by Deserialization
-	 *
-	 * @param jsonElement
-	 * @param objDispatch
-	 * @param eleDispatch
-	 */
-	private void loadCanvasElements(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
-			HashMap<Integer, HolonElement> eleDispatch) {
-		// TODO Auto-generated method stub
-
-		JsonObject object = jsonElement.getAsJsonObject();
-
-		HolonElement temp = model.getGson().fromJson(object.get("properties"), HolonElement.class);
-		initElements(temp);
-		// id which Object it was stored before
-		int stored = object.get("ID").getAsInt();
-		// lookup that object
-		HolonObject temp2 = (HolonObject) objDispatch.get(stored);
-		// add it
-		objC.addElement(temp2, temp);
-		// store element also inside a table
-		eleDispatch.put(temp.getId(), temp);
-	}
-
-	/**
-	 * Load a given Edge by Deserialization
-	 *
-	 * @param type
-	 * @param jsonElement
-	 * @param objDispatch
-	 */
-	private void loadEdge(EDGETYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
-		// TODO Auto-generated method stub
-		JsonObject object = jsonElement.getAsJsonObject();
-		CpsEdge temp = model.getGson().fromJson(object.get("properties"), CpsEdge.class);
-		initCpsEdge(temp);
-		// look for A and B inside the Table
-		temp.setA(objDispatch.get(object.get("A").getAsInt()));
-		temp.setB(objDispatch.get(object.get("B").getAsInt()));
-
-		int sav = 0;
-
-		switch (type) {
-		case CANVAS:
-			// if in canvas add it into the canvas but delete connection before
-			model.getEdgesOnCanvas().add(temp);
-			break;
-		case CONNECTION:
-			// if no duplicates in connection store them into the given A and B
-			if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getA().getConnections()))
-				temp.getA().getConnections().add(temp);
-			if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getB().getConnections()))
-				temp.getB().getConnections().add(temp);
-			break;
-		case NODE:
-			// put it into given nodeofnode
-			sav = object.get("ID").getAsInt();
-			((CpsUpperNode) objDispatch.get(sav)).getNodeEdges().add(temp);
-			break;
-		case OLD:
-			// same as above
-			sav = object.get("ID").getAsInt();
-			((CpsUpperNode) objDispatch.get(sav)).getOldEdges().add(temp);
-			break;
-		default:
-			break;
-		}
-
-		if (object.get("connection").getAsBoolean() && !type.equals(EDGETYPE.CONNECTION)) {
-			temp.getA().getConnections().add(temp);
-			temp.getB().getConnections().add(temp);
-		}
-
-	}
-
-	/**
-	 * Load a Unitgraph by Deserialization
-	 *
-	 * @param type
-	 * @param jsonElement
-	 * @param objDispatch
-	 * @param eleDispatch
-	 */
-	private void loadUnitGraph(GRAPHTYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
-			HashMap<Integer, HolonElement> eleDispatch) {
-		// TODO Auto-generated method stub
-
-		JsonObject object = jsonElement.getAsJsonObject();
-		List<String> keys = getKeys(object);
-		String p = null;
-		int mid, x, y = 0;
-
-		LinkedList<Point> graphpoint = new LinkedList<>();
-		int sav = 0;
-		// foreach Point in the graph restore it
-		for (String k : keys) {
-			if (!k.equals("ID")) {
-				p = object.get(k).getAsString();
-				mid = p.indexOf(':');
-				x = Integer.parseInt(p.substring(0, mid));
-				y = Integer.parseInt(p.substring(mid + 1, p.length()));
-				graphpoint.add(new Point(x, y));
-			} else
-				// else its an ID
-				sav = object.get(k).getAsInt();
-
-		}
-
-		switch (type) {
-		case SWITCH:
-			HolonSwitch sw = (HolonSwitch) objDispatch.get(sav);
-			sw.setGraphPoints(graphpoint);
-			break;
-		case ELEMENT:
-			HolonElement ele = eleDispatch.get(sav);
-			ele.setGraphPoints(graphpoint);
-			break;
-		default:
-			break;
-		}
-	}
-
-	private void loadStatisticGraph(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
-		// TODO Auto-generated method stub
-		JsonObject object = jsonElement.getAsJsonObject();
-		model.getGraphTable().clear();
-		model.getStatisticData().add(object);
-	}
-
-	private void loadTracked(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
-		// TODO Auto-generated method stub
-		JsonObject object = jsonElement.getAsJsonObject();
-		List<String> keys = getKeys(object);
-
-		for (String k : keys) {
-			int id = object.get(k).getAsInt();
-			model.getTrackingObj().add(objDispatch.get(id));
-			model.addObjectsToGraphListeners();
-			if (objDispatch.get(id) instanceof HolonObject) {
-				((HolonObject) objDispatch.get(id)).updateTrackingInfo();
-			}
-		}
-
-	}
-
-	private File readArchive(String path, File src) throws IOException, ArchiveException {
-		File tmp = Files.createTempDirectory("tmpHolon").toFile();
-		tmp.deleteOnExit();
-		InputStream input = new FileInputStream(src);
-		ArchiveInputStream stream = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP,
-				input);
-
-		ArchiveEntry entry = stream.getNextEntry();
-		while (entry != null) {
-			// String entryName = checkOS(entry.getName());
-			File file = new File(tmp, entry.getName());
-			file.getParentFile().mkdirs();
-			OutputStream output = new FileOutputStream(file);
-			IOUtils.copy(stream, output);
-			output.close();
-			// file.createNewFile();
-			entry = stream.getNextEntry();
-		}
-
-		stream.close();
-		input.close();
-
-		return tmp;
-	}
-
-	private String checkOS(String entryName) {
-		// TODO Auto-generated method stub
-		String os = System.getProperty("os.name").toLowerCase();
-		String ret = entryName;
-		String partition = System.getProperty("user.home");
-
-		if (!ret.contains("HolonGUI"))
-			return ret;
-
-		if (os.contains("windows")) {
-			ret = ret.replace("/", "\\");
-			ret = System.getProperty("user.home") + "\\.config"
-					+ ret.substring(ret.indexOf("\\HolonGUI\\"), ret.length());
-
-		}
-		if (os.contains("mac")) {
-			// dosmth
-			ret = ret.replace("\\", "/");
-			ret = System.getProperty("user.home") + "/.config" + ret.substring(ret.indexOf("/HolonGUI/"), ret.length());
-		}
-		if (os.contains("linux")) {
-			// dosmth
-			ret = ret.replace("\\", "/");
-			ret = System.getProperty("user.home") + "/.config" + ret.substring(ret.indexOf("/HolonGUI/"), ret.length());
-		}
-		if (os.contains("solaris")) {
-			// dosmth
-		}
-		return ret;
-	}
-
-	/**
-	 * Init new Arrays which havent been serialized along the object
-	 *
-	 * @param obj
-	 */
-	public void initObjects(AbstractCpsObject obj) {
-
-		obj.setConnections(new ArrayList<CpsEdge>());
-		obj.setTags(new ArrayList<Integer>());
-		obj.setPseudoTags(new ArrayList<Integer>());
-
-		if (obj instanceof HolonObject) {
-			((HolonObject) obj).setElements(new ArrayList<HolonElement>());
-
-			((HolonObject) obj).setTrackingProd(new float[100]);
-			((HolonObject) obj).setTrackingCons(new float[100]);
-		}
-
-		if (obj instanceof HolonSwitch) {
-			((HolonSwitch) obj).setActiveAt(true);
-			((HolonSwitch) obj).setGraphPoints(new LinkedList<Point>());
-		}
-
-		if (obj instanceof CpsUpperNode) {
-			((CpsUpperNode) obj).setNodes(new ArrayList<AbstractCpsObject>());
-			((CpsUpperNode) obj).setNodeEdges(new ArrayList<CpsEdge>());
-			((CpsUpperNode) obj).setOldEdges(new ArrayList<CpsEdge>());
-			((CpsUpperNode) obj).setNodesIdx(new HashMap<Integer, Integer>());
-		}
-	}
-
-	/**
-	 * Init Elements
-	 *
-	 * @param ele
-	 */
-	public void initElements(HolonElement ele) {
-
-		ele.setAvailableEnergyPerElementAt(ele.getEnergyPerElement());
-		ele.setGraphPoints(new LinkedList<Point>());
-	}
-
-	/**
-	 * Init Edges
-	 *
-	 * @param edge
-	 */
-	public void initCpsEdge(CpsEdge edge) {
-		edge.setTags(new ArrayList<Integer>());
-		edge.setPseudoTag(new ArrayList<Integer>());
-		edge.setA(null);
-		edge.setB(null);
-	}
-
-	/**
-	 * Get Set of Keys
-	 *
-	 * @param json
-	 * @return
-	 */
-	public List<String> getKeys(JsonObject json) {
-		return json.entrySet().stream().map(i -> i.getKey()).collect(Collectors.toCollection(ArrayList::new));
-	}
-
-	/**
-	 * enum Mode.
-	 */
-	public enum MODE {
-		COMPLETE, PARTIAL, CATEGORY
-	}
-
-	public enum EDGETYPE {
-		CANVAS, CONNECTION, NODE, OLD
-	}
-
-	public enum GRAPHTYPE {
-		SWITCH, ELEMENT
-	}
+    private Model model;
+    private CategoryController cgC;
+    private CanvasController cvsC;
+    private ObjectController objC;
+    private NodeController uppC;
+    private MultiPurposeController mpC;
+    private JsonParser parser;
+
+    /**
+     * Constructor.
+     *
+     * @param model Model
+     * @param cg    CategoryController
+     * @param cvs   CanvasController
+     * @param obj   ObjectController
+     * @param mp    MultiPurposeController
+     */
+    LoadController(Model model, CategoryController cg, CanvasController cvs, ObjectController obj,
+                   NodeController uppC, MultiPurposeController mp) {
+        this.model = model;
+        this.cgC = cg;
+        this.cvsC = cvs;
+        this.objC = obj;
+        this.uppC = uppC;
+        this.mpC = mp;
+        this.parser = new JsonParser();
+    }
+
+    /**
+     * Reads the the JSON File and load the state into the Model.
+     *
+     * @param path the Path
+     * @throws IOException exception
+     */
+    void readSave(String path) throws IOException, ArchiveException {
+
+        File src = new File(path);
+        File folder = readArchive(src);
+        folder.deleteOnExit();
+        String trim = folder.getPath().substring(0,
+                folder.getPath().lastIndexOf(folder.getName()) + folder.getName().length());
+
+        forwardFiles(folder, trim);
+
+    }
+
+    void readJson(String path) throws IOException {
+        JsonObject json = (JsonObject) parser.parse(new FileReader(path));
+        // get all keys via stream
+        List<String> keys = getKeys(json);
+        List<String> edges = keys.stream().filter(key -> key.contains("EDGE"))
+                .collect(Collectors.toCollection(ArrayList::new));
+
+        HashMap<Integer, AbstractCpsObject> objDispatch = new HashMap<>();
+        HashMap<Integer, HolonElement> eleDispatch = new HashMap<>();
+
+        initialize(json);
+        forwardObjects(keys, json, objDispatch, eleDispatch);
+        forwardEdges(edges, json, objDispatch);
+
+    }
+
+    /**
+     * Loads the Files from the Savefile
+     *
+     * @param trim the part of the file's path to be trimmed
+     * @throws IOException if anythings goes wrong reading the files
+     */
+    private void forwardFiles(File folder, String trim) throws IOException {
+        for (File file : folder.listFiles()) {
+            File dst = new File(
+                    System.getProperty("user.home") + "/.config/HolonGUI/" + file.getPath().replace(trim, ""));
+
+            if (file.getName().contains(".json"))
+                readJson(file.getPath());
+            else if (file.isDirectory())
+                forwardFiles(file, trim);
+            else {
+                dst.getParentFile().mkdirs();
+                Files.copy(file.toPath(), dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
+            }
+
+        }
+    }
+
+    /**
+     * distribute the Edges
+     */
+    private void forwardEdges(List<String> edges, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch) {
+
+        List<String> conn = new ArrayList<>();
+
+        for (String edge : edges) {
+            if (edge.contains("CVSEDGE"))
+                loadEdge(EDGETYPE.CANVAS, json.get(edge), objDispatch);
+            if (edge.contains("CONNEDGE"))
+                conn.add(edge);
+            if (edge.contains("NODE"))
+                loadEdge(EDGETYPE.NODE, json.get(edge), objDispatch);
+            if (edge.contains("OLD"))
+                loadEdge(EDGETYPE.OLD, json.get(edge), objDispatch);
+        }
+
+        for (String edge : conn) {
+            loadEdge(EDGETYPE.CONNECTION, json.get(edge), objDispatch);
+        }
+
+    }
+
+    /**
+     * Distribute the given keys for right processing
+     */
+    private void forwardObjects(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
+                                HashMap<Integer, HolonElement> eleDispatch) {
+        for (String key : keys) {
+            if (key.contains("CATEGORY"))
+                loadCategory(json.get(key));
+            if (key.contains("CGOBJECT"))
+                loadCategoryObject(json.get(key));
+            if (key.contains("CGELEMENT"))
+                loadCategoryElements(json.get(key));
+            if (key.contains("CVSOBJECT"))
+                loadCanvasObject(json.get(key), objDispatch);
+            if (key.contains("CVSELEMENT"))
+                loadCanvasElements(json.get(key), objDispatch, eleDispatch);
+            if (key.contains("SWUNITGRAPH"))
+                loadUnitGraph(GRAPHTYPE.SWITCH, json.get(key), objDispatch, null);
+            if (key.contains("ELEUNITGRAPH"))
+                loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
+            if (key.contains("TRACKED"))
+                loadTracked(json.get(key), objDispatch);
+            if (key.contains("STATSGRAPH"))
+                loadStatisticGraph(json.get(key));
+        }
+
+    }
+
+    /**
+     * Init the Global Parameters
+     */
+    private void initialize(JsonObject json) {
+
+        switch (MODE.valueOf(json.get("MODE").getAsString())) {
+            case COMPLETE:
+                model.setCvsObjIdx(new HashMap<>());
+                model.setObjectsOnCanvas(new ArrayList<>());
+                model.setEdgesOnCanvas(new ArrayList<>());
+                model.setTrackingObj(new ArrayList<>());
+                model.setStatisticData(new ArrayList<>());
+                model.setHashcodeMap(new HashMap<>());
+                model.setCanvasX(json.get("CANVAS_SIZE_X").getAsInt());
+                model.setCanvasX(json.get("CANVAS_SIZE_Y").getAsInt());
+                IdCounter.setCounter(json.get("IDCOUNTER").getAsInt());
+                IdCounterElem.setCounter(json.get("IDCOUNTERELEMENT").getAsInt());
+                break;
+            case PARTIAL:
+                model.setCvsObjIdx(new HashMap<>());
+                model.setObjectsOnCanvas(new ArrayList<>());
+                model.setEdgesOnCanvas(new ArrayList<>());
+                model.setHashcodeMap(new HashMap<>());
+                model.setCanvasX(json.get("CANVAS_SIZE_X").getAsInt());
+                model.setCanvasX(json.get("CANVAS_SIZE_Y").getAsInt());
+                IdCounter.setCounter(json.get("IDCOUNTER").getAsInt());
+                IdCounterElem.setCounter(json.get("IDCOUNTERELEMENT").getAsInt());
+                break;
+            case CATEGORY:
+                model.setCgIdx(new HashMap<>());
+                model.setCategories(new ArrayList<>());
+
+            default:
+                break;
+        }
+
+    }
+
+    /**
+     * Load a given Category
+     */
+    private void loadCategory(JsonElement jsonElement) {
+        if (mpC.searchCat(jsonElement.getAsString()) == null)
+            cgC.addCategory(new Category(jsonElement.getAsString()));
+    }
+
+    /**
+     * Load a given Object in Category by Deserialization
+     */
+    private void loadCategoryObject(JsonElement jsonElement) {
+        AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
+        temp.setImage(checkOS(temp.getImage()));
+        initObjects(temp);
+        if (mpC.searchCatObj(mpC.searchCat(temp.getSav()), temp.getObjName()) != null)
+            cgC.deleteObject(temp.getSav(), temp.getObjName());
+        cgC.addObject(mpC.searchCat(temp.getSav()), temp);
+
+    }
+
+    /**
+     * Load a given Element in Category by Deserialization
+     */
+    private void loadCategoryElements(JsonElement jsonElement) {
+        HolonElement temp = model.getGson().fromJson(jsonElement.getAsJsonObject().get("properties").getAsJsonObject(),
+                HolonElement.class);
+        initElements(temp);
+        objC.addElementIntoCategoryObject(temp.getSaving().getKey(), temp.getSaving().getValue(), temp);
+    }
+
+    /**
+     * Load a given Object in Canvas by Deserialization
+     */
+    private void loadCanvasObject(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
+        AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
+        initObjects(temp);
+        temp.setImage(checkOS(temp.getImage()));
+        if (temp instanceof CpsUpperNode) {
+            model.getHashcodeMap().put(jsonElement.getAsJsonObject().get("hash").getAsInt(), (CpsUpperNode) temp);
+            ((CpsUpperNode) temp).setLeftBorder(jsonElement.getAsJsonObject().get("properties").getAsJsonObject().get("leftBorder").getAsInt());
+        }
+        // if its stored before on the canvas just put it there
+        if (temp.getSav().equals("CVS")) {
+            cvsC.addObject(temp);
+
+        } else {
+            // else look up the table and put it into the right Uppernode
+            CpsUpperNode temp2 = (CpsUpperNode) objDispatch.get(Integer.parseInt(temp.getSav()));
+            uppC.addObjectInUpperNode(temp, temp2);
+        }
+
+        objDispatch.put(temp.getId(), temp);
+
+    }
+
+    /**
+     * Load a given Element in Canvas by Deserialization
+     */
+    private void loadCanvasElements(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
+                                    HashMap<Integer, HolonElement> eleDispatch) {
+
+        JsonObject object = jsonElement.getAsJsonObject();
+
+        HolonElement temp = model.getGson().fromJson(object.get("properties"), HolonElement.class);
+        initElements(temp);
+        // id which Object it was stored before
+        int stored = object.get("ID").getAsInt();
+        // lookup that object
+        HolonObject temp2 = (HolonObject) objDispatch.get(stored);
+        // add it
+        objC.addElement(temp2, temp);
+        // store element also inside a table
+        eleDispatch.put(temp.getId(), temp);
+    }
+
+    /**
+     * Load a given Edge by Deserialization
+     */
+    private void loadEdge(EDGETYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
+        JsonObject object = jsonElement.getAsJsonObject();
+        CpsEdge temp = model.getGson().fromJson(object.get("properties"), CpsEdge.class);
+        initCpsEdge(temp);
+        // look for A and B inside the Table
+        temp.setA(objDispatch.get(object.get("A").getAsInt()));
+        temp.setB(objDispatch.get(object.get("B").getAsInt()));
+
+        int sav;
+
+        switch (type) {
+            case CANVAS:
+                // if in canvas add it into the canvas but delete connection before
+                model.getEdgesOnCanvas().add(temp);
+                break;
+            case CONNECTION:
+                // if no duplicates in connection store them into the given A and B
+                if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getA().getConnections()))
+                    temp.getA().getConnections().add(temp);
+                if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getB().getConnections()))
+                    temp.getB().getConnections().add(temp);
+                break;
+            case NODE:
+                // put it into given nodeofnode
+                sav = object.get("ID").getAsInt();
+                ((CpsUpperNode) objDispatch.get(sav)).getNodeEdges().add(temp);
+                break;
+            case OLD:
+                // same as above
+                sav = object.get("ID").getAsInt();
+                ((CpsUpperNode) objDispatch.get(sav)).getOldEdges().add(temp);
+                break;
+            default:
+                break;
+        }
+
+        if (object.get("connection").getAsBoolean() && !type.equals(EDGETYPE.CONNECTION)) {
+            temp.getA().getConnections().add(temp);
+            temp.getB().getConnections().add(temp);
+        }
+
+    }
+
+    /**
+     * Load a Unitgraph by Deserialization
+     */
+    private void loadUnitGraph(GRAPHTYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
+                               HashMap<Integer, HolonElement> eleDispatch) {
+
+        JsonObject object = jsonElement.getAsJsonObject();
+        List<String> keys = getKeys(object);
+        String p;
+        int mid, x, y;
+
+        LinkedList<Point> graphpoint = new LinkedList<>();
+        int sav = 0;
+        // foreach Point in the graph restore it
+        for (String k : keys) {
+            if (!k.equals("ID")) {
+                p = object.get(k).getAsString();
+                mid = p.indexOf(':');
+                x = Integer.parseInt(p.substring(0, mid));
+                y = Integer.parseInt(p.substring(mid + 1, p.length()));
+                graphpoint.add(new Point(x, y));
+            } else
+                // else its an ID
+                sav = object.get(k).getAsInt();
+
+        }
+
+        switch (type) {
+            case SWITCH:
+                HolonSwitch sw = (HolonSwitch) objDispatch.get(sav);
+                sw.setGraphPoints(graphpoint);
+                break;
+            case ELEMENT:
+                HolonElement ele = eleDispatch.get(sav);
+                ele.setGraphPoints(graphpoint);
+                break;
+            default:
+                break;
+        }
+    }
+
+    private void loadStatisticGraph(JsonElement jsonElement) {
+        JsonObject object = jsonElement.getAsJsonObject();
+        model.getGraphTable().clear();
+        model.getStatisticData().add(object);
+    }
+
+    private void loadTracked(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
+        JsonObject object = jsonElement.getAsJsonObject();
+        List<String> keys = getKeys(object);
+
+        for (String k : keys) {
+            int id = object.get(k).getAsInt();
+            model.getTrackingObj().add(objDispatch.get(id));
+            model.addObjectsToGraphListeners();
+            if (objDispatch.get(id) instanceof HolonObject) {
+                ((HolonObject) objDispatch.get(id)).updateTrackingInfo();
+            }
+        }
+
+    }
+
+    private File readArchive(File src) throws IOException, ArchiveException {
+        File tmp = Files.createTempDirectory("tmpHolon").toFile();
+        tmp.deleteOnExit();
+        InputStream input = new FileInputStream(src);
+        ArchiveInputStream stream = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP,
+                input);
+
+        ArchiveEntry entry = stream.getNextEntry();
+        while (entry != null) {
+            // String entryName = checkOS(entry.getName());
+            File file = new File(tmp, entry.getName());
+            file.getParentFile().mkdirs();
+            OutputStream output = new FileOutputStream(file);
+            IOUtils.copy(stream, output);
+            output.close();
+            // file.createNewFile();
+            entry = stream.getNextEntry();
+        }
+
+        stream.close();
+        input.close();
+
+        return tmp;
+    }
+
+    private String checkOS(String entryName) {
+        String os = System.getProperty("os.name").toLowerCase();
+        String ret = entryName;
+//        String partition = System.getProperty("user.home");
+
+        if (!ret.contains("HolonGUI"))
+            return ret;
+
+        if (os.contains("windows")) {
+            ret = ret.replace("/", "\\");
+            ret = System.getProperty("user.home") + "\\.config"
+                    + ret.substring(ret.indexOf("\\HolonGUI\\"), ret.length());
+
+        }
+        if (os.contains("mac")) {
+            // dosmth
+            ret = ret.replace("\\", "/");
+            ret = System.getProperty("user.home") + "/.config" + ret.substring(ret.indexOf("/HolonGUI/"), ret.length());
+        }
+        if (os.contains("linux")) {
+            // dosmth
+            ret = ret.replace("\\", "/");
+            ret = System.getProperty("user.home") + "/.config" + ret.substring(ret.indexOf("/HolonGUI/"), ret.length());
+        }
+//        if (os.contains("solaris")) {
+//            // dosmth
+//        }
+        return ret;
+    }
+
+    /**
+     * Init new Arrays which haven't been serialized along the object
+     */
+    void initObjects(AbstractCpsObject obj) {
+
+        obj.setConnections(new ArrayList<>());
+        obj.setTags(new ArrayList<>());
+        obj.setPseudoTags(new ArrayList<>());
+
+        if (obj instanceof HolonObject) {
+            ((HolonObject) obj).setElements(new ArrayList<>());
+
+            ((HolonObject) obj).setTrackingProd(new float[100]);
+            ((HolonObject) obj).setTrackingCons(new float[100]);
+        }
+
+        if (obj instanceof HolonSwitch) {
+            ((HolonSwitch) obj).setActiveAt(true);
+            ((HolonSwitch) obj).setGraphPoints(new LinkedList<>());
+        }
+
+        if (obj instanceof CpsUpperNode) {
+            ((CpsUpperNode) obj).setNodes(new ArrayList<>());
+            ((CpsUpperNode) obj).setNodeEdges(new ArrayList<>());
+            ((CpsUpperNode) obj).setOldEdges(new ArrayList<>());
+            ((CpsUpperNode) obj).setNodesIdx(new HashMap<>());
+        }
+    }
+
+    /**
+     * Init Elements (set available energy, set new graph points)
+     *
+     * @param ele the element to be initialized
+     */
+    void initElements(HolonElement ele) {
+        ele.setAvailableEnergyPerElementAt(ele.getEnergyPerElement());
+        ele.setGraphPoints(new LinkedList<>());
+    }
+
+    /**
+     * Init Edges (set tags and reset source and target)
+     *
+     * @param edge the edge to be initialized
+     */
+    void initCpsEdge(CpsEdge edge) {
+        edge.setTags(new ArrayList<>());
+        edge.setPseudoTag(new ArrayList<>());
+        edge.setA(null);
+        edge.setB(null);
+    }
+
+    /**
+     * Get Set of Keys
+     *
+     * @return the keys from the json object
+     */
+    List<String> getKeys(JsonObject json) {
+        return json.entrySet().stream().map(i -> i.getKey()).collect(Collectors.toCollection(ArrayList::new));
+    }
+
+    /**
+     * enum Mode.
+     */
+    public enum MODE {
+        COMPLETE, PARTIAL, CATEGORY
+    }
+
+    public enum EDGETYPE {
+        CANVAS, CONNECTION, NODE, OLD
+    }
+
+    public enum GRAPHTYPE {
+        SWITCH, ELEMENT
+    }
 
 }

+ 30 - 92
src/ui/controller/NodeController.java

@@ -1,36 +1,33 @@
 package ui.controller;
 
-import java.awt.Point;
-import java.util.ArrayList;
-import java.util.Iterator;
-
 import classes.AbstractCpsObject;
 import classes.CpsEdge;
 import classes.CpsUpperNode;
 import classes.Position;
 import ui.model.Model;
 
-public class NodeController {
+import java.awt.*;
+import java.util.ArrayList;
+import java.util.Iterator;
+
+
+class NodeController {
 
 	private Model model;
 	private CanvasController cvs;
 	private MultiPurposeController mpC;
 	private Point point;
 
-	public NodeController(Model model, CanvasController cvs, MultiPurposeController mpC) {
-		// TODO Auto-generated constructor stub
-		this.model = model;
+    NodeController(Model model, CanvasController cvs, MultiPurposeController mpC) {
+        this.model = model;
 		this.cvs = cvs;
 		this.mpC = mpC;
 	}
 
 	/**
 	 * Add a CpsUpperNode into Canvas
-	 * 
-	 * @param nodeName
-	 * @param upperNode
 	 */
-	public void doUpperNode(String nodeName, CpsUpperNode upperNode, ArrayList<AbstractCpsObject> toGroup) {
+    void doUpperNode(String nodeName, CpsUpperNode upperNode, ArrayList<AbstractCpsObject> toGroup) {
 
 		CpsUpperNode node = new CpsUpperNode(nodeName);
 		node.setPosition(calculatePos(toGroup));
@@ -46,11 +43,8 @@ public class NodeController {
 
 	/**
 	 * Delete a CpsUpperNode from the Canvas
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
-	public void undoUpperNode(CpsUpperNode node, CpsUpperNode upperNode) {
+    void undoUpperNode(CpsUpperNode node, CpsUpperNode upperNode) {
 
 		Position old = calculatePos(node.getNodes());
 		Position p = node.getPosition();
@@ -67,9 +61,6 @@ public class NodeController {
 
 	/**
 	 * Put selected Nodes inside the Upper Node
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
 	private void makeNodeOfNodes(CpsUpperNode node, CpsUpperNode upperNode, ArrayList<AbstractCpsObject> toGroup) {
 
@@ -77,18 +68,13 @@ public class NodeController {
 		ArrayList<CpsEdge> toDelete = new ArrayList<>();
 
 		// Put all selected Nodes into the Upper Node
-		for (Iterator<AbstractCpsObject> it = toGroup.iterator(); it.hasNext();) {
-
-			// füge Neue Objecte in Neuen Node hinzu
-			AbstractCpsObject obj = it.next();
+        for (AbstractCpsObject obj : toGroup) {
+            // füge Neue Objecte in Neuen Node hinzu
 			addObjectInUpperNode(obj, node);
 		}
 
 		// Füge die Edges die Alle Objekte vorher verbunden hat in neuen Node
-		for (Iterator<CpsEdge> it = (upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges())
-				.iterator(); it.hasNext();) {
-
-			CpsEdge edge = it.next();
+        for (CpsEdge edge : (upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges())) {
 
 			// kopiere edge in UpperNode
 			if (nodes.contains(edge.getA()) && nodes.contains(edge.getB())) {
@@ -113,12 +99,8 @@ public class NodeController {
 	/**
 	 * Transfer all relevant data from Node into the next higher layer of Node
 	 * (upperNode)
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
 	private void unmakeNodesOfNodes(CpsUpperNode node, CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
 		// add all nodes into upperNode
 
 		for (CpsEdge edge : node.getConnections()) {
@@ -149,9 +131,6 @@ public class NodeController {
 	/**
 	 * Look for adjacent Nodes connected with the new CpsUpperNode and make
 	 * Connections
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
 	private void makeAdjacent(CpsUpperNode node, CpsUpperNode upperNode, ArrayList<AbstractCpsObject> toGroup) {
 
@@ -213,12 +192,8 @@ public class NodeController {
 
 	/**
 	 * Restore the Old Connections from the adjacent Object
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
 	private void unmakeAdjacent(CpsUpperNode node, CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
 		ArrayList<CpsEdge> toDelete = new ArrayList<>();
 		ArrayList<CpsEdge> lostEdges = new ArrayList<>();
 		ArrayList<CpsEdge> foundEdges = (upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges());
@@ -227,10 +202,8 @@ public class NodeController {
 				: upperNode.getNodes());
 
 		// für jede Edge aus upperNode die Node enthält tu sie in toDelete
-		for (Iterator<CpsEdge> it = foundEdges.iterator(); it.hasNext();) {
-
-			CpsEdge edge = it.next();
-			if (edge.getA().equals(node) || edge.getB().equals(node))
+        for (CpsEdge edge : foundEdges) {
+            if (edge.getA().equals(node) || edge.getB().equals(node))
 				toDelete.add(edge);
 
 		}
@@ -315,14 +288,9 @@ public class NodeController {
 
 	/**
 	 * Just checking if an Egde already exists
-	 * 
-	 * @param a
-	 * @param b
-	 * @param list
-	 * @return
 	 */
-	public boolean lookforDuplicates(AbstractCpsObject a, AbstractCpsObject b, ArrayList<CpsEdge> list) {
-		for (CpsEdge cpsEdge : list) {
+    boolean lookforDuplicates(AbstractCpsObject a, AbstractCpsObject b, ArrayList<CpsEdge> list) {
+        for (CpsEdge cpsEdge : list) {
 			if ((a.equals(cpsEdge.getA()) && b.equals(cpsEdge.getB()))
 					|| (b.equals(cpsEdge.getA()) && a.equals(cpsEdge.getB())))
 				return true;
@@ -332,9 +300,6 @@ public class NodeController {
 
 	/**
 	 * Backups Old Edges into next lower layer in Current UpperNode anymore
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
 	private void backupOldEdges(CpsUpperNode node, CpsUpperNode upperNode) {
 
@@ -384,9 +349,6 @@ public class NodeController {
 
 	/**
 	 * Restore Old Edges into next higher layer of UpperNode
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
 	private void restoreOldEdges(CpsUpperNode node, CpsUpperNode upperNode) {
 
@@ -418,10 +380,8 @@ public class NodeController {
 
 	/**
 	 * Calculate new Position of the Upper Node
-	 * 
-	 * @return
 	 */
-	public Position calculatePos(ArrayList<AbstractCpsObject> toGroup) {
+    Position calculatePos(ArrayList<AbstractCpsObject> toGroup) {
 
 		Position pos = new Position(0, 0);
 
@@ -438,8 +398,6 @@ public class NodeController {
 
 	/**
 	 * Removes the Given Obj from current Layer and adjusts the idx
-	 * @param obj
-	 * @param upperNode
 	 */
 	private void removeForNodeOfNode(AbstractCpsObject obj, CpsUpperNode upperNode) {
 
@@ -481,24 +439,18 @@ public class NodeController {
 
 	/**
 	 * Add a Object into a CpsUpperNode
-	 * 
-	 * @param object
-	 * @param upperNode
 	 */
-	public void addObjectInUpperNode(AbstractCpsObject object, CpsUpperNode upperNode) {
-		object.setSav("" + upperNode.getId());
+    void addObjectInUpperNode(AbstractCpsObject object, CpsUpperNode upperNode) {
+        object.setSav("" + upperNode.getId());
 		upperNode.getNodesIdx().put(object.getId(), upperNode.getNodes().size());
 		upperNode.getNodes().add(object);
 	}
 
 	/**
 	 * Delete a AbstactCpsObject from CPSUpperNode
-	 * 
-	 * @param object
-	 * @param upperNode
 	 */
-	public void deleteObjectInUpperNode(AbstractCpsObject object, CpsUpperNode upperNode) {
-		CpsEdge e = null;
+    void deleteObjectInUpperNode(AbstractCpsObject object, CpsUpperNode upperNode) {
+        CpsEdge e = null;
 		for (AbstractCpsObject cps : upperNode.getNodes()) {
 			for (CpsEdge p : cps.getConnections()) {
 				if (p.getA() == object || p.getB() == object) {
@@ -518,22 +470,16 @@ public class NodeController {
 
 	/**
 	 * Add Edge in UpperNode
-	 * 
-	 * @param edge
-	 * @param upperNode
 	 */
-	public void addEdge(CpsEdge edge, CpsUpperNode upperNode) {
-		upperNode.getNodeEdges().add(edge);
+    void addEdge(CpsEdge edge, CpsUpperNode upperNode) {
+        upperNode.getNodeEdges().add(edge);
 	}
 
 	/**
 	 * Delete Edge in UpperNode
-	 * 
-	 * @param edge
-	 * @param upperNode
 	 */
-	public void deleteEdge(CpsEdge edge, CpsUpperNode upperNode) {
-		edge.getA().getConnections().remove(edge);
+    void deleteEdge(CpsEdge edge, CpsUpperNode upperNode) {
+        edge.getA().getConnections().remove(edge);
 		edge.getB().getConnections().remove(edge);
 		upperNode.getNodeEdges().remove(edge);
 		if (edge.getA() instanceof CpsUpperNode || edge.getB() instanceof CpsUpperNode)
@@ -542,23 +488,18 @@ public class NodeController {
 
 	/**
 	 * Connect Objects outside of current Layer to Objects inside the Layer
-	 * 
-	 * @param a
-	 * @param b
 	 */
-	public void connectNodes(CpsEdge edge, CpsUpperNode upperNode) {
-		// keine Connections nötig, da automatisch erzeugt bei Instanziierung
+    void connectNodes(CpsEdge edge, CpsUpperNode upperNode) {
+        // keine Connections nötig, da automatisch erzeugt bei Instanziierung
 		// mache diese Edge auch in OldEdges rein des aktuellen CpsUpperNodes
 		upperNode.getOldEdges().add(edge);
 	}
 	
 	/**
 	 * Disconnect Objects outside of current Layer to Objects inside the Layer
-	 * @param edge
-	 * @param upperNode
 	 */
-	public void disconnectNodes(CpsEdge edge, CpsUpperNode upperNode) {
-		edge.getA().getConnections().remove(edge);
+    void disconnectNodes(CpsEdge edge, CpsUpperNode upperNode) {
+        edge.getA().getConnections().remove(edge);
 		edge.getB().getConnections().remove(edge);
 		if (upperNode != null)
 			upperNode.getOldEdges().remove(edge);
@@ -566,11 +507,8 @@ public class NodeController {
 	
 	/**
 	 * If Position is out of boundaries adjust it
-	 * @param temp
-	 * @param upperNode
 	 */
 	private void updatePosition(AbstractCpsObject temp, CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
 		int x = temp.getPosition().x - point.x;
 		int y = temp.getPosition().y - point.y;
 

+ 44 - 122
src/ui/controller/SaveController.java

@@ -1,51 +1,19 @@
 package ui.controller;
 
-import java.awt.Color;
-import java.awt.Point;
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
+import classes.*;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
 import org.apache.commons.compress.archivers.ArchiveException;
 import org.apache.commons.compress.archivers.ArchiveOutputStream;
 import org.apache.commons.compress.archivers.ArchiveStreamFactory;
 import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
 import org.apache.commons.compress.utils.IOUtils;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonPrimitive;
-
-import TypeAdapter.AbstractCpsObjectAdapter;
-import TypeAdapter.ColorAdapter;
-import TypeAdapter.PositionAdapter;
-import classes.AbstractCpsObject;
-import classes.Category;
-import classes.CpsEdge;
-import classes.CpsUpperNode;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.IdCounter;
-import classes.IdCounterElem;
-import classes.Position;
-import classes.TrackedDataSet;
 import ui.model.Model;
-import ui.view.StatisticGraph;
-import ui.view.StatisticGraphPanel;
+
+import java.awt.*;
+import java.io.*;
+import java.util.*;
+import java.util.List;
 
 /**
  * Controller for Storage.
@@ -54,50 +22,30 @@ import ui.view.StatisticGraphPanel;
  */
 public class SaveController {
 
-	public enum MODE {
-		COMPLETE, PARTIAL, CATEGORY
-	}
-
-	public enum TYPE {
-		CATEGORY, CANVAS
-	}
-
-	public enum EDGETYPE {
-		CANVAS, CONNECTION, NODE, OLD, LAYER
-	}
-
-	public enum NUMTYPE {
-		CATEGORY, OBJECT, ELEMENT, EDGE, CONNECTION, NODEEDGE, OLDEDGE, UNITGRAPH, STATSGRAPH
-	}
-
-	public enum GRAPHTYPE {
-		SWITCH, ELEMENT
-	}
-
 	private Model model;
 	private int nCat, nObj, nEle, nEdge, nConn, nNodeEdge, nOldEdge, nUnitGraph, nStatsGraph;
 
 	/**
 	 * Constructor.
-	 * 
+	 *
 	 * @param model
 	 *            the Model
 	 */
-	public SaveController(Model model) {
+	SaveController(Model model) {
 		this.model = model;
 	}
 
 	/**
 	 * Writes the current State of the Modelling into a JSON File which can be
 	 * loaded.
-	 * 
+	 *
 	 * @param path
 	 *            the Path
-	 * 
+	 *
 	 * @throws IOException
 	 *             exception
 	 */
-	public void writeSave(String path) throws IOException, ArchiveException {
+	void writeSave(String path) throws IOException, ArchiveException {
 
 		File dst = new File(path);
 		File holonFile = File.createTempFile("tmp", ".json");
@@ -130,13 +78,13 @@ public class SaveController {
 
 	/**
 	 * Writes the Autosave File.
-	 * 
+	 *
 	 * @param path
 	 *            the Path
 	 * @throws IOException
 	 *             Exception
 	 */
-	public void writeAutosave(String path) throws IOException {
+	void writeAutosave(String path) throws IOException {
 
 		initNumeration();
 		JsonObject file = new JsonObject();
@@ -152,11 +100,8 @@ public class SaveController {
 
 	/**
 	 * Writes the Category File in Case of Changes
-	 * 
-	 * @param path
-	 * @throws IOException
 	 */
-	public void writeCategory(String path) throws IOException {
+	void writeCategory(String path) throws IOException {
 
 		initNumeration();
 		JsonObject file = new JsonObject();
@@ -174,12 +119,8 @@ public class SaveController {
 	/**
 	 * Write needed default parameter into the JsonObject. Can be extended later
 	 * on
-	 * 
-	 * @param mode
-	 * @param file
 	 */
 	private void initialize(MODE mode, JsonObject file) {
-		// TODO Auto-generated method stub
 		switch (mode) {
 		case COMPLETE:
 			file.add("MODE", new JsonPrimitive(mode.name()));
@@ -205,11 +146,8 @@ public class SaveController {
 
 	/**
 	 * Store all Categories and Object into a Json File via Serialization
-	 * 
-	 * @param file
 	 */
 	private void storeCategory(JsonObject file) {
-		// TODO Auto-generated method stub
 		// forall categories store them into the jsontree
 		for (Category cat : model.getCategories()) {
 			String key = "CATEGORY" + getNumerator(NUMTYPE.CATEGORY);
@@ -228,11 +166,8 @@ public class SaveController {
 
 	/**
 	 * Travers through all Objects via BFS and Stores everything relevant
-	 * 
-	 * @param file
 	 */
 	private void storeCanvas(JsonObject file) {
-		// TODO Auto-generated method stub
 		ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
 		AbstractCpsObject u = null;
 		// put all objects into queue since there is not starting object
@@ -278,12 +213,8 @@ public class SaveController {
 
 	/**
 	 * Save wanted Data
-	 * 
-	 * @param stream
-	 * @throws IOException
 	 */
 	private void storeData(ArchiveOutputStream stream) throws IOException {
-		// TODO Auto-generated method stub
 		File images = new File(System.getProperty("user.home") + "/.config/HolonGUI/Images");
 		File background = new File(System.getProperty("user.home") + "/.config/HolonGUI/BackgroundImages");
 		addFilesToSave(images, stream);
@@ -293,14 +224,8 @@ public class SaveController {
 
 	/**
 	 * Stores Category or Canvas Elements into Json
-	 * 
-	 * @param type
-	 * @param gson
-	 * @param file
-	 * @param obj
 	 */
-	public void elementsToJson(TYPE type, JsonObject file, AbstractCpsObject obj) {
-		// TODO Auto-generated method stub
+	void elementsToJson(TYPE type, JsonObject file, AbstractCpsObject obj) {
 		JsonObject temp = new JsonObject();
 		String key = null;
 		// forall elements store them into json and include the id of the object
@@ -329,10 +254,8 @@ public class SaveController {
 
 	/**
 	 * Put the UnitGraphs of Switches or Elements into Json
-	 * 
-	 * @param ele
 	 */
-	public void unitgraphToJson(GRAPHTYPE type, JsonObject file, int id, LinkedList<Point> graph) {
+	void unitgraphToJson(GRAPHTYPE type, JsonObject file, int id, LinkedList<Point> graph) {
 
 		JsonObject temp = new JsonObject();
 		String key = null;
@@ -359,14 +282,8 @@ public class SaveController {
 
 	/**
 	 * Canvas-Edge, Connections, Node-Edge and Old-Edges to json
-	 * 
-	 * @param type
-	 * @param file
-	 * @param id
-	 * @param arr
 	 */
-	public void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
-		// TODO Auto-generated method stub
+	private void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
 		String k = null;
 		boolean b = false;
 		JsonObject temp = new JsonObject();
@@ -408,7 +325,6 @@ public class SaveController {
 	}
 
 	private void trackedToJson(JsonObject file) {
-		// TODO Auto-generated method stub
 		JsonObject temp = new JsonObject();
 		String key = "TRACKED";
 		// forall points add them
@@ -420,17 +336,16 @@ public class SaveController {
 	}
 
 	private void statisticgraphToJson(JsonObject file) {
-		// TODO Auto-generated method stub
 		JsonObject temp = new JsonObject();
 
-		List<String> keys = model.getGraphTable().keySet().stream().collect(Collectors.toCollection(ArrayList::new));
+		List<String> keys = new ArrayList<>(model.getGraphTable().keySet());
 
 		for (String k : keys) {
 			JsonObject dataSet = new JsonObject();
 			for (int i = 0; i < model.getGraphTable().get(k).getStatGraph().getDataSets().size(); i++) {
 				TrackedDataSet set = model.getGraphTable().get(k).getStatGraph().getDataSets().get(i);
 				AbstractCpsObject cps = set.getCpsObject();
-				
+
 				dataSet.add("ID", (cps == null ? null : new JsonPrimitive(cps.getId())));
 				dataSet.add("COLOR", model.getGson().toJsonTree(set.getColor(), Color.class));
 				dataSet.add("PROPERTY", new JsonPrimitive(set.getProperty()));
@@ -447,10 +362,6 @@ public class SaveController {
 
 	/**
 	 * Differs Between Single file or whole Directory to Store
-	 * 
-	 * @param src
-	 * @param stream
-	 * @throws IOException
 	 */
 	private void addFilesToSave(File src, ArchiveOutputStream stream) throws IOException {
 		if (!src.exists())
@@ -470,14 +381,9 @@ public class SaveController {
 
 	/**
 	 * Add a File into the Archive
-	 * 
-	 * @param src
-	 * @param stream
-	 * @param dir
-	 * @throws IOException
 	 */
 	private void addFileToSave(File src, ArchiveOutputStream stream, boolean dir) throws IOException {
-		String entryName = (dir == true ? src.getCanonicalPath() : src.getName());
+		String entryName = (dir ? src.getCanonicalPath() : src.getName());
 
 		entryName = checkOS(entryName);
 
@@ -491,7 +397,6 @@ public class SaveController {
 	}
 
 	private String checkOS(String entryName) {
-		// TODO Auto-generated method stub
 		String os = System.getProperty("os.name").toLowerCase();
 		String ret = entryName;
 		String partition = null;
@@ -518,17 +423,14 @@ public class SaveController {
 	/**
 	 * Just initialize the Numerators for the Json Keys. Maybe bad Style..
 	 */
-	public void initNumeration() {
+	void initNumeration() {
 		this.nCat = this.nObj = this.nEle = this.nEdge = this.nConn = this.nNodeEdge = this.nOldEdge = this.nStatsGraph = 0;
 	}
 
 	/**
 	 * Get the wanted numerator and increment it
-	 * 
-	 * @param type
-	 * @return
 	 */
-	public int getNumerator(NUMTYPE type) {
+	int getNumerator(NUMTYPE type) {
 
 		switch (type) {
 		case CATEGORY:
@@ -556,4 +458,24 @@ public class SaveController {
 		return -1;
 	}
 
+	public enum MODE {
+		COMPLETE, PARTIAL, CATEGORY
+	}
+
+	public enum TYPE {
+		CATEGORY, CANVAS
+	}
+
+	public enum EDGETYPE {
+		CANVAS, CONNECTION, NODE, OLD, LAYER
+	}
+
+	public enum NUMTYPE {
+		CATEGORY, OBJECT, ELEMENT, EDGE, CONNECTION, NODEEDGE, OLDEDGE, UNITGRAPH, STATSGRAPH
+	}
+
+	public enum GRAPHTYPE {
+		SWITCH, ELEMENT
+	}
+
 }

+ 19 - 14
src/ui/controller/SimulationManager.java

@@ -116,8 +116,11 @@ public class SimulationManager {
     }
 
     /**
-     * search for all flexible devices in the network and turn them on, until wasted energy = 0
-     * or all devices have been examined
+     * search for all flexible devices in the network and turn them on, until energy surplus = 0
+     * or all devices have been examined.
+     *
+     * This code could be compressed (cases inside over- and underproduction are the same), but we decided that it
+     * is better readable this way
      *
      * @param subNet        the subnet
      * @param energySurplus the current surplus of energy
@@ -129,18 +132,17 @@ public class SimulationManager {
                 // if this element is flexible and active (can be considered for calculations)
                 if (holonEl.isFlexible() && holonEl.isActive()) {
                     float energyAvailableSingle = holonEl.getAvailableEnergyAt(timestep);
-                    float energyAvailableMult = energyAvailableSingle * holonEl.getAmount();
-
+                    float energyAvailableMultiple = energyAvailableSingle * holonEl.getAmount();
 
                     // ------------- flexible consumer / OVERPRODUCTION -------------
-                    if (energyAvailableMult < 0 && energySurplus > 0) {
+                    if (energyAvailableMultiple < 0 && energySurplus > 0) {
 
                         // if there is more wasted energy than energy that this device can give, give all energy available
-                        if (Math.abs(energyAvailableMult) <= Math.abs(energySurplus)) {
-                            energySurplus += energyAvailableMult;
+                        if (Math.abs(energyAvailableMultiple) <= Math.abs(energySurplus)) {
+                            energySurplus += energyAvailableMultiple;
                             // set the new energy consumption to the maximum
                             holonEl.setEnergyPerElement(energyAvailableSingle);
-                            flexDevicesTurnedOnThisTurn.put(holonEl, energyAvailableMult);
+                            flexDevicesTurnedOnThisTurn.put(holonEl, energyAvailableMultiple);
                         }
                         // else: we just need to turn on part of the flexible energy available
                         else {
@@ -150,18 +152,17 @@ public class SimulationManager {
                             holonEl.setEnergyPerElement(energyNeeded / holonEl.getAmount());
                             flexDevicesTurnedOnThisTurn.put(holonEl, energyNeeded);
                         }
-
                     }
 
-                    // ------------- flexible producer / UNDEPRODUCTION -------------
-                    else if (energyAvailableMult > 0 && energySurplus < 0) {
+                    // ------------- flexible producer / UNDERPRODUCTION -------------
+                    else if (energyAvailableMultiple > 0 && energySurplus < 0) {
 
                         // if there is more energy needed than this device can give, give all the energy available
-                        if (Math.abs(energyAvailableMult) <= Math.abs(energySurplus)) {
-                            energySurplus += energyAvailableMult;
+                        if (Math.abs(energyAvailableMultiple) <= Math.abs(energySurplus)) {
+                            energySurplus += energyAvailableMultiple;
                             // set the new energy consumption to the maximum
                             holonEl.setEnergyPerElement(energyAvailableSingle);
-                            flexDevicesTurnedOnThisTurn.put(holonEl, energyAvailableMult);
+                            flexDevicesTurnedOnThisTurn.put(holonEl, energyAvailableMultiple);
                         }
                         // else: we just need to turn on part of the flexible energy available
                         else {
@@ -180,6 +181,10 @@ public class SimulationManager {
                     break;
                 }
             }
+
+            if (energySurplus == 0) {
+                break;
+            }
         }
     }
 

+ 0 - 1
src/ui/model/Model.java

@@ -909,7 +909,6 @@ public class Model {
      * Initialize the Gson with wanted parameters
      */
     private void initGson() {
-        // TODO Auto-generated method stub
         GsonBuilder builder = new GsonBuilder();
         builder.serializeNulls();
         builder.excludeFieldsWithoutExposeAnnotation();

+ 51 - 73
src/ui/view/AddElementPopUp.java

@@ -1,26 +1,14 @@
 package ui.view;
 
-import java.awt.BorderLayout;
-import java.awt.Color;
-import java.awt.FlowLayout;
-import java.awt.Image;
-import javax.swing.JButton;
-import javax.swing.JDialog;
-import javax.swing.JPanel;
-import javax.swing.border.EmptyBorder;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JTextField;
-import javax.swing.ImageIcon;
-
 import classes.AbstractCpsObject;
 import classes.HolonElement;
 import classes.HolonObject;
-import java.awt.event.ActionListener;
+
+import javax.swing.*;
+import javax.swing.border.EmptyBorder;
+import java.awt.*;
 import java.awt.event.KeyEvent;
 import java.awt.event.KeyListener;
-import java.awt.event.ActionEvent;
 
 /**
  * popup for adding an Holon Element to a holon Object.
@@ -40,12 +28,12 @@ public class AddElementPopUp extends JDialog {
 	private HolonElement hl;
 	private AbstractCpsObject tempCps;
 
-	/**
-	 * Launch the application.
-	 *
-	 * @param args
-	 *            standard
-	 */
+//	/**
+//	 * Launch the application.
+//	 *
+//	 * @param args
+//	 *            standard
+//	 */
 //	public static void main(String[] args) {
 //		try {
 //
@@ -60,8 +48,8 @@ public class AddElementPopUp extends JDialog {
 	/**
 	 * Create the dialog.
 	 */
-	public AddElementPopUp() {
-		super((java.awt.Frame) null, true);
+    AddElementPopUp() {
+        super((java.awt.Frame) null, true);
 		this.setIconImage(new ImageIcon(this.getClass().getResource("/Images/Dummy_House.png")).getImage()
 				.getScaledInstance(30, 30, Image.SCALE_SMOOTH));
 		setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);
@@ -89,14 +77,10 @@ public class AddElementPopUp extends JDialog {
 		elementName.addKeyListener(new KeyListener() {
 			@Override
 			public void keyPressed(KeyEvent arg0) {
-				// TODO Auto-generated method stub
-
 			}
 
 			@Override
 			public void keyReleased(KeyEvent e) {
-				// TODO Auto-generated method stub
-
 			}
 
 			@Override
@@ -125,43 +109,41 @@ public class AddElementPopUp extends JDialog {
 			getContentPane().add(buttonPane, BorderLayout.SOUTH);
 			{
 				JButton okButton = new JButton("OK");
-				okButton.addActionListener(new ActionListener() {
-					public void actionPerformed(ActionEvent arg0) {
-						boolean repeated = false;
-						for (HolonElement e : ((HolonObject) tempCps).getElements()) {
-							if (elementName.getText().equals(e.getEleName())) {
-								repeated = true;
-								break;
-							}
-						}
-						if (elementName.getText().length() != 0 && !repeated) {
-							try {
-								float energy = Float.parseFloat(providedEnergy.getText().toString());
-								int elementAmount = Integer.parseInt(amount.getText().toString());
-								hl = new HolonElement(elementName.getText().toString(), elementAmount, energy);
-
-								dispose();
-							} catch (NumberFormatException e) {
-								JOptionPane.showMessageDialog(new JFrame(), Languages.getLanguage()[68]);
-							}
-						} else {
-							// JOptionPane.showMessageDialog(new JFrame(),
-							// "Please enter a Name");
-
-							if (elementName.getText().length() == 0) {
-								JLabel errorString = new JLabel(Languages.getLanguage()[69]);
-								errorString.setBounds(240, 8, 100, 20);
-								contentPanel.add(errorString);
-							} else if (repeated) {
-								JLabel errorString = new JLabel(Languages.getLanguage()[70]);
-								errorString.setBounds(250, 8, 100, 20);
-								contentPanel.add(errorString);
-							}
-							elementName.setBackground(new Color(255, 50, 50));
-						}
-					}
-				});
-				okButton.setActionCommand("OK");
+                okButton.addActionListener(arg0 -> {
+                    boolean repeated = false;
+                    for (HolonElement e : ((HolonObject) tempCps).getElements()) {
+                        if (elementName.getText().equals(e.getEleName())) {
+                            repeated = true;
+                            break;
+                        }
+                    }
+                    if (elementName.getText().length() != 0 && !repeated) {
+                        try {
+                            float energy = Float.parseFloat(providedEnergy.getText());
+                            int elementAmount = Integer.parseInt(amount.getText());
+                            hl = new HolonElement(elementName.getText(), elementAmount, energy);
+
+                            dispose();
+                        } catch (NumberFormatException e) {
+                            JOptionPane.showMessageDialog(new JFrame(), Languages.getLanguage()[68]);
+                        }
+                    } else {
+                        // JOptionPane.showMessageDialog(new JFrame(),
+                        // "Please enter a Name");
+
+                        if (elementName.getText().length() == 0) {
+                            JLabel errorString = new JLabel(Languages.getLanguage()[69]);
+                            errorString.setBounds(240, 8, 100, 20);
+                            contentPanel.add(errorString);
+                        } else if (repeated) {
+                            JLabel errorString = new JLabel(Languages.getLanguage()[70]);
+                            errorString.setBounds(250, 8, 100, 20);
+                            contentPanel.add(errorString);
+                        }
+                        elementName.setBackground(new Color(255, 50, 50));
+                    }
+                });
+                okButton.setActionCommand("OK");
 				buttonPane.add(okButton);
 				getRootPane().setDefaultButton(okButton);
 			}
@@ -169,12 +151,8 @@ public class AddElementPopUp extends JDialog {
 				JButton cancelButton = new JButton(Languages.getLanguage()[71]);
 				cancelButton.setActionCommand("Cancel");
 				buttonPane.add(cancelButton);
-				cancelButton.addActionListener(new ActionListener() {
-					public void actionPerformed(ActionEvent e) {
-						dispose();
-					}
-				});
-			}
+                cancelButton.addActionListener(e -> dispose());
+            }
 		}
 
 	}
@@ -185,8 +163,8 @@ public class AddElementPopUp extends JDialog {
 	 * @param cps
 	 *            actual Cps
 	 */
-	public void setActualCps(AbstractCpsObject cps) {
-		this.tempCps = cps;
+    void setActualCps(AbstractCpsObject cps) {
+        this.tempCps = cps;
 	}
 
 	/**

+ 78 - 97
src/ui/view/AddObjectPopUp.java

@@ -10,10 +10,11 @@ import javax.swing.*;
 import javax.swing.border.EmptyBorder;
 import javax.swing.filechooser.FileNameExtensionFilter;
 import java.awt.*;
-import java.awt.event.*;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
 import java.io.*;
-import java.net.URLDecoder;
-import java.security.CodeSource;
 import java.util.ArrayList;
 
 /**
@@ -24,7 +25,6 @@ import java.util.ArrayList;
 public class AddObjectPopUp extends JDialog {
 
 	private static final long serialVersionUID = 1L;
-	private final JPanel contentPanel = new JPanel();
 	private AddElementPopUp addElement;
 	private JTextField objectName;
 	private JTextField sourcePath;
@@ -32,7 +32,7 @@ public class AddObjectPopUp extends JDialog {
 	private DefaultListModel listModel;
 	private JList list;
 	private String imagePath;
-	private HolonObject theObject;
+	//	private HolonObject theObject;
 	private Control controller;
 	private File selectedFile = null;
 	private String filePath = " ";
@@ -42,12 +42,12 @@ public class AddObjectPopUp extends JDialog {
 	private boolean editState;
 	private boolean imageChanged = false;
 
-	/**
-	 * Launch the application.
-	 *
-	 * @param args
-	 *            standard
-	 */
+//	/**
+//	 * Launch the application.
+//	 *
+//	 * @param args
+//	 *            standard
+//	 */
 //	public static void main(String[] args) {
 //		try {
 //			AddObjectPopUp dialog = new AddObjectPopUp(false, null, null);
@@ -68,7 +68,7 @@ public class AddObjectPopUp extends JDialog {
 	 * @param cat
 	 *            the categorie
 	 */
-	public AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat) {
+	AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat) {
 		toEdit = obj;
 		editState = edit;
 		this.setIconImage(new ImageIcon(this.getClass().getResource("/Images/Dummy_House.png")).getImage()
@@ -76,6 +76,7 @@ public class AddObjectPopUp extends JDialog {
 		setBounds(100, 100, 450, 342);
 		setLocationRelativeTo(this.getParent());
 		getContentPane().setLayout(new BorderLayout());
+		JPanel contentPanel = new JPanel();
 		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
 		getContentPane().add(contentPanel, BorderLayout.CENTER);
 		contentPanel.setLayout(null);
@@ -92,13 +93,11 @@ public class AddObjectPopUp extends JDialog {
 			objectName.addKeyListener(new KeyListener() {
 				@Override
 				public void keyPressed(KeyEvent arg0) {
-					// TODO Auto-generated method stub
 
 				}
 
 				@Override
 				public void keyReleased(KeyEvent e) {
-					// TODO Auto-generated method stub
 
 				}
 
@@ -135,14 +134,10 @@ public class AddObjectPopUp extends JDialog {
 			sourcePath.addKeyListener(new KeyListener() {
 				@Override
 				public void keyPressed(KeyEvent arg0) {
-					// TODO Auto-generated method stub
-
 				}
 
 				@Override
 				public void keyReleased(KeyEvent e) {
-					// TODO Auto-generated method stub
-
 				}
 
 				@Override
@@ -161,8 +156,7 @@ public class AddObjectPopUp extends JDialog {
 				sourcePath.setText(filePath);
 				ImageIcon icon = new ImageIcon(
 						new ImageIcon(filePath).getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH));
-				if (icon != null)
-					lblImagePreview.setIcon(icon);
+				lblImagePreview.setIcon(icon);
 			}
 			sourcePath.setBounds(148, 77, 271, 20);
 			contentPanel.add(sourcePath);
@@ -170,19 +164,17 @@ public class AddObjectPopUp extends JDialog {
 		}
 		{
 			JButton btnAddDefaultElement = new JButton(Languages.getLanguage()[61]);
-			btnAddDefaultElement.addActionListener(new ActionListener() {
-				public void actionPerformed(ActionEvent arg0) {
-					addElement = new AddElementPopUp();
-					addElement.setActualCps(toEdit);
-					addElement.setVisible(true);
-					HolonElement hl = addElement.getElement();
-					hl.setSaving(new Pair<String, String>(givenCategory, objectName.getText()));
-					// if (hl != null) {
-					// hl.setSav(givenCategory);
-					// }
-					// hl.setObj(objectName.getText());
-					addElement(hl);
-				}
+			btnAddDefaultElement.addActionListener(actionEvent -> {
+				addElement = new AddElementPopUp();
+				addElement.setActualCps(toEdit);
+				addElement.setVisible(true);
+				HolonElement hl = addElement.getElement();
+				hl.setSaving(new Pair<>(givenCategory, objectName.getText()));
+				// if (hl != null) {
+				// hl.setSav(givenCategory);
+				// }
+				// hl.setObj(objectName.getText());
+				addElement(hl);
 			});
 
 			btnAddDefaultElement.setBounds(270, 144, 142, 23);
@@ -212,13 +204,11 @@ public class AddObjectPopUp extends JDialog {
 		}
 		{
 			JButton btnNewButton = new JButton(Languages.getLanguage()[62]);
-			btnNewButton.addActionListener(new ActionListener() {
-				public void actionPerformed(ActionEvent e) {
-					int selectedIndex = list.getSelectedIndex();
-					if (selectedIndex != -1) {
-						listModel.remove(selectedIndex);
-						hElements.remove(selectedIndex);
-					}
+			btnNewButton.addActionListener(actionEvent -> {
+				int selectedIndex = list.getSelectedIndex();
+				if (selectedIndex != -1) {
+					listModel.remove(selectedIndex);
+					hElements.remove(selectedIndex);
 				}
 			});
 			btnNewButton.setBounds(270, 182, 142, 27);
@@ -233,7 +223,7 @@ public class AddObjectPopUp extends JDialog {
 				JButton okButton = new JButton("OK");
 				okButton.addMouseListener(new MouseAdapter() {
 					public void mouseClicked(MouseEvent e) {
-						Component frame = null;
+//						Component frame = null;
 						if (objectName.getText().length() > 0) {
 							if (sourcePath.getText().equals(filePath)) {
 								imagePath = filePath;
@@ -257,8 +247,6 @@ public class AddObjectPopUp extends JDialog {
 												objectName.getText(), hElements, imagePath);
 									}
 								} catch (Exception e2) {
-									// TODO: handle exception
-
 								}
 
 								// controller.addObjectCategory(controller.searchCategory(givenCategory),
@@ -286,37 +274,33 @@ public class AddObjectPopUp extends JDialog {
 				JButton cancelButton = new JButton(Languages.getLanguage()[63]);
 				cancelButton.setActionCommand("Cancel");
 				buttonPane.add(cancelButton);
-				cancelButton.addActionListener(new ActionListener() {
-					public void actionPerformed(ActionEvent e) {
-						dispose();
-					}
-				});
+				cancelButton.addActionListener(e -> dispose());
 			}
 		}
 	}
 
-	/**
-	 * Get Jar Containing Folder.
-	 *
-	 * @param aclass aClass
-	 * @return String
-	 * @throws Exception Exception
-	 */
-	public static String getJarContainingFolder(Class aclass) throws Exception {
-		CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();
-
-		File jarFile;
-
-		if (codeSource.getLocation() != null) {
-			jarFile = new File(codeSource.getLocation().toURI());
-		} else {
-			String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
-			String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
-			jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
-			jarFile = new File(jarFilePath);
-		}
-		return jarFile.getParentFile().getAbsolutePath();
-	}
+//	/**
+//	 * Get Jar Containing Folder.
+//	 *
+//	 * @param aclass aClass
+//	 * @return String
+//	 * @throws Exception Exception
+//	 */
+//	public static String getJarContainingFolder(Class aclass) throws Exception {
+//		CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();
+//
+//		File jarFile;
+//
+//		if (codeSource.getLocation() != null) {
+//			jarFile = new File(codeSource.getLocation().toURI());
+//		} else {
+//			String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
+//			String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
+//			jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
+//			jarFile = new File(jarFilePath);
+//		}
+//		return jarFile.getParentFile().getAbsolutePath();
+//	}
 
 	/**
 	 * adds a Holon Element.
@@ -324,7 +308,7 @@ public class AddObjectPopUp extends JDialog {
 	 * @param hl
 	 *            the HolonElement
 	 */
-	public void addElement(HolonElement hl) {
+	private void addElement(HolonElement hl) {
 		hElements.add(hl);
 		listModel.addElement(hl.getAmount() + "x: " + hl.getEleName() + " " + hl.getEnergyPerElement() + "U");
 	}
@@ -332,8 +316,7 @@ public class AddObjectPopUp extends JDialog {
 	/**
 	 * Choose the file.
 	 */
-	protected void fileChooser() {
-		// TODO Auto-generated method stub
+	private void fileChooser() {
 		JFileChooser fileChooser = new JFileChooser();
 		FileNameExtensionFilter filter = new FileNameExtensionFilter("png, jpg or jpeg", "png", "jpg", "jpeg");
 		fileChooser.setFileFilter(filter);
@@ -355,9 +338,9 @@ public class AddObjectPopUp extends JDialog {
 	/**
 	 * Copies the File.
 	 */
-	protected void copieFile() {
-		InputStream inStream = null;
-		OutputStream outStream = null;
+	private void copieFile() {
+		InputStream inStream;
+		OutputStream outStream;
 		try {
 			File source = new File(filePath);
 			File dest = new File(System.getProperty("user.home") + "/.config/HolonGUI/Images/");
@@ -374,34 +357,32 @@ public class AddObjectPopUp extends JDialog {
 				outStream.write(buffer, 0, length);
 			}
 
-			if (inStream != null)
-				inStream.close();
-			if (outStream != null)
-				outStream.close();
+			inStream.close();
+			outStream.close();
 			System.out.println("File Copied..");
 		} catch (IOException eex) {
 			eex.printStackTrace();
 		}
 	}
 
-	/**
-	 * Edit the Information.
-	 *
-	 * @param obj
-	 *            the CpsObject
-	 */
-	public void editInformation(HolonObject obj) {
-		objectName.setText(obj.getName());
-	}
+//	/**
+//	 * Edit the Information.
+//	 *
+//	 * @param obj
+//	 *            the CpsObject
+//	 */
+//	public void editInformation(HolonObject obj) {
+//		objectName.setText(obj.getName());
+//	}
 
-	/**
-	 * Return the Object.
-	 * 
-	 * @return the CpsObject
-	 */
-	public HolonObject getObject() {
-		return theObject;
-	}
+//	/**
+//	 * Return the Object.
+//	 *
+//	 * @return the CpsObject
+//	 */
+//	public HolonObject getObject() {
+//		return theObject;
+//	}
 
 	/**
 	 * Sets the Controller.

+ 43 - 48
src/ui/view/GUI.java

@@ -177,7 +177,6 @@ public class GUI implements CategoryListener {
     private JSplitPane tempSplit;
     private boolean initSplit = true;
     private String catOfObjToBeEdited;
-    private FlexiblePane flexPane;
     private UpperNodeCanvas unc;
     private JPanel contentPane;
     private String holonEleNamesDisplayed = "None ";
@@ -209,14 +208,13 @@ public class GUI implements CategoryListener {
     private String saveBeforeNew = "Do you want to save your current data?";
     private String eraseCategory = "Do you really want to delete the Category ";
     private String selectObjBeforeErase = "Please select a Category or an Object in order to delete something.";
-    private Component horizontalStrut = Box.createHorizontalStrut(20);
 
     /**
      * Create the application.
      *
      * @param control the Controller
      */
-    public GUI(Control control) {
+    GUI(Control control) {
         this.controller = control;
         this.model = control.getModel();
         statSplitPane = new StatisticPanel(controller);
@@ -236,32 +234,32 @@ public class GUI implements CategoryListener {
         updCon = new UpdateController(model, controller);
     }
 
-    /**
-     * Adds a Popup.
-     *
-     * @param component Component
-     * @param popup     PopupMenu
-     */
-    private static void addPopup(Component component, final JPopupMenu popup) {
-        component.addMouseListener(new MouseAdapter() {
-            public void mousePressed(MouseEvent e) {
-                if (e.isPopupTrigger()) {
-                    showMenu(e);
-                }
-            }
-
-            public void mouseReleased(MouseEvent e) {
-                if (e.isPopupTrigger()) {
-                    showMenu(e);
-                }
-            }
-
-            private void showMenu(MouseEvent e) {
-                popup.show(e.getComponent(), e.getX(), e.getY());
-            }
-
-        });
-    }
+//    /**
+//     * Adds a Popup.
+//     *
+//     * @param component Component
+//     * @param popup     PopupMenu
+//     */
+//    private static void addPopup(Component component, final JPopupMenu popup) {
+//        component.addMouseListener(new MouseAdapter() {
+//            public void mousePressed(MouseEvent e) {
+//                if (e.isPopupTrigger()) {
+//                    showMenu(e);
+//                }
+//            }
+//
+//            public void mouseReleased(MouseEvent e) {
+//                if (e.isPopupTrigger()) {
+//                    showMenu(e);
+//                }
+//            }
+//
+//            private void showMenu(MouseEvent e) {
+//                popup.show(e.getComponent(), e.getX(), e.getY());
+//            }
+//
+//        });
+//    }
 
     /**
      * Initialize the contents of the frame.
@@ -823,7 +821,7 @@ public class GUI implements CategoryListener {
 
         toolBarGraph.add(lblSelectedElement);
         toolBarGraph.add(elementGraph);
-        horizontalStrut = Box.createHorizontalStrut(toolBarGraph.getWidth() - resetGraphBtn.getWidth());
+        Component horizontalStrut = Box.createHorizontalStrut(toolBarGraph.getWidth() - resetGraphBtn.getWidth());
 
         toolBarGraph.add(horizontalStrut);
         resetGraphBtn.setHorizontalAlignment(SwingConstants.RIGHT);
@@ -1084,7 +1082,6 @@ public class GUI implements CategoryListener {
                 contentPane.updateUI();
                 unitGraph.repaint();
             } catch (Exception e) {
-
             }
         });
         /***********************
@@ -1426,7 +1423,7 @@ public class GUI implements CategoryListener {
                             JOptionPane.showMessageDialog(new JFrame(),
                                     Languages.getLanguage()[57] + selectedOption + ".");
                         }
-                        if (selectedNode.getLevel() == 1) {
+                        if (selectedNode != null && selectedNode.getLevel() == 1) {
                             AbstractCpsObject tmp = new HolonObject("");
                             addObjectPopUP = new AddObjectPopUp(false, tmp, null);
                             addObjectPopUP.setVisible(true);
@@ -1440,7 +1437,6 @@ public class GUI implements CategoryListener {
                         break;
                 }
             } catch (Exception e) {
-                // TODO: handle exception
             }
             tree.repaint();
         });
@@ -1598,10 +1594,10 @@ public class GUI implements CategoryListener {
         mntmOpen.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evt) {
-                menuFileExitActionPerformed(evt);
+                menuFileExitActionPerformed();
             }
 
-            private void menuFileExitActionPerformed(ActionEvent evt) {
+            private void menuFileExitActionPerformed() {
                 JFileChooser fileChooser = new JFileChooser();
                 JFrame test = new JFrame();
                 FileNameExtensionFilter holonFilter = new FileNameExtensionFilter("Holon Save File(*.holon)", "holon");
@@ -1630,10 +1626,10 @@ public class GUI implements CategoryListener {
         mntmSave.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evt) {
-                menuSaveActionPerformed(evt);
+                menuSaveActionPerformed();
             }
 
-            private void menuSaveActionPerformed(ActionEvent evt) {
+            private void menuSaveActionPerformed() {
                 JFileChooser fileChooser = new JFileChooser();
                 JFrame test = new JFrame();
                 FileNameExtensionFilter holonFilter = new FileNameExtensionFilter("Holon Save File(*.holon)", "holon");
@@ -1697,10 +1693,10 @@ public class GUI implements CategoryListener {
         mntmUndo.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evt) {
-                menuUndoActionPerformed(evt);
+                menuUndoActionPerformed();
             }
 
-            private void menuUndoActionPerformed(ActionEvent evt) {
+            private void menuUndoActionPerformed() {
                 try {
                     controller.loadAutoSave(controller.getUndoSave());
                     canvas.repaint();
@@ -1708,7 +1704,6 @@ public class GUI implements CategoryListener {
                     repaintGraphAfterUndoRedo();
                     hideScrollGraph();
                 } catch (IOException e) {
-                    // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
@@ -1717,10 +1712,10 @@ public class GUI implements CategoryListener {
         mntmRedo.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evt) {
-                menuRedoActionPerformed(evt);
+                menuRedoActionPerformed();
             }
 
-            private void menuRedoActionPerformed(ActionEvent evt) {
+            private void menuRedoActionPerformed() {
                 try {
                     controller.loadAutoSave(controller.getRedoSave());
                     canvas.repaint();
@@ -1760,7 +1755,7 @@ public class GUI implements CategoryListener {
 //        tabbedPaneInnerSplit.addTab("Main Grid", null);
         tabbedPaneOriginal.addTab("Statistics", statScrollPane);
         tabbedPaneOriginal.addTab("Holon", holonCanvas);
-        flexPane = new FlexiblePane(controller);
+        FlexiblePane flexPane = new FlexiblePane(controller);
         controller.setFlexiblePane(flexPane);
         controller.getModel().getObjectListeners().add(flexPane);
         tabbedPaneOriginal.addTab("Flexibility", flexPane);
@@ -2213,9 +2208,9 @@ public class GUI implements CategoryListener {
         return getScrollPaneFromTabbedPane(index);
     }
 
-    private JScrollPane getScrollPaneFromTabbedPane(JTabbedPane tabbedPane) {
-        return getScrollPaneFromTabbedPane(tabbedPane, -1);
-    }
+//    private JScrollPane getScrollPaneFromTabbedPane(JTabbedPane tabbedPane) {
+//        return getScrollPaneFromTabbedPane(tabbedPane, -1);
+//    }
 
     private JScrollPane getScrollPaneFromTabbedPane() {
         return getScrollPaneFromTabbedPane(-1);
@@ -2247,8 +2242,8 @@ public class GUI implements CategoryListener {
     /**
      * if flexibility was turned on, then active needs to be turned off, the energy currently produced/consumed
      *
-     * @param eleBTemp
-     * @param selectedValueBY
+     * @param eleBTemp element that needs to be updated
+     * @param selectedValueBY the y value in the table
      */
     private void updateElementTableAfterChange(HolonElement eleBTemp, int selectedValueBY) {
         model.getSingleTable().setValueAt(eleBTemp.isFlexible(), selectedValueBY, 6);

+ 41 - 81
src/ui/view/HolonCanvas.java

@@ -1,27 +1,5 @@
 package ui.view;
 
-import java.awt.Color;
-import java.awt.Dimension;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.RenderingHints;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.awt.event.MouseMotionListener;
-import java.awt.event.MouseWheelEvent;
-import java.awt.event.MouseWheelListener;
-import java.util.ArrayList;
-
-import javax.swing.JCheckBox;
-import javax.swing.JComboBox;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.event.ChangeEvent;
-import javax.swing.event.ChangeListener;
-
-import classes.AbstractCpsObject;
 import classes.HolonBody;
 import classes.SubNet;
 import classes.Vector2d;
@@ -29,6 +7,11 @@ import ui.controller.Control;
 import ui.controller.HolonCanvasController;
 import ui.model.Model;
 
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.*;
+import java.util.ArrayList;
+
 public class HolonCanvas extends JPanel implements MouseWheelListener, MouseListener, MouseMotionListener {
 
 	/**
@@ -36,19 +19,12 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 	 */
 	private static final long serialVersionUID = 1L;
 
-	// Rendering
-	private Graphics2D g2;
-
 	// Ball objects
 	private ArrayList<HolonBody> bodies = new ArrayList<>();
 	private int subCount;
 
-	// Frames
-	private int currentFrameRate;
-
 	private long previousTime = System.currentTimeMillis();
 	private long currentTime = previousTime;
-	private long elapsedTime;
 	private long totalElapsedTime = 0;
 	private int frameCount = 0;
 	private Dimension center;
@@ -59,21 +35,19 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 	private Model model;
 	private JComboBox<String> combo = new JComboBox<>();
 	private int comboChoice = 0;
-	private String info;
-	private int bodyNr;
-	private final JLabel lblBodyInfo = new JLabel("Holon Info:");
 	private JCheckBox chckbxSort = new JCheckBox("sort by size");
 	private boolean sizeChange = false;
 	private HolonBody toDrag;
-	
-	public HolonCanvas(Model mod, Control control) {
-		// Wire up Events
+
+    HolonCanvas(Model mod, Control control) {
+        // Wire up Events
 		this.controller = control;
 		this.model = mod;
 		
 		hCController = new HolonCanvasController(mod);
 
-		add(lblBodyInfo);
+        JLabel lblBodyInfo = new JLabel("Holon Info:");
+        add(lblBodyInfo);
 		this.add(combo);
 		subnets = controller.getSimManager().getSubNets();
 		subCount = subnets.size();
@@ -92,23 +66,12 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 		combo.addItem("Nr. of Producers");
 		combo.addItem("Nr. of active Elements");
 
-		combo.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				comboChoice = combo.getSelectedIndex();
-			}
-		});
-		this.addMouseListener(this);
+        combo.addActionListener(e -> comboChoice = combo.getSelectedIndex());
+        this.addMouseListener(this);
 		this.addMouseMotionListener(this);
 
-		chckbxSort.addChangeListener(new ChangeListener() {
-
-			@Override
-			public void stateChanged(ChangeEvent e) {
-				sizeChange = true;
-			}
-		});
-		add(chckbxSort);
+        chckbxSort.addChangeListener(e -> sizeChange = true);
+        add(chckbxSort);
 	}
 
 	// Start Render and Update Threads
@@ -132,12 +95,12 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 		}
 
 		currentTime = System.currentTimeMillis();
-		elapsedTime = (currentTime - previousTime); // elapsed time in seconds
-		totalElapsedTime += elapsedTime;
+        long elapsedTime = (currentTime - previousTime);
+        totalElapsedTime += elapsedTime;
 
 		if (totalElapsedTime > 1000) {
-			currentFrameRate = frameCount;
-			frameCount = 0;
+//			int currentFrameRate = frameCount;
+            frameCount = 0;
 			totalElapsedTime = 0;
 		}
 
@@ -160,21 +123,22 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 		previousTime = currentTime;
 		frameCount++;
 		repaint();
-	}	
+	}
 
-	public void render(Graphics g) {
-		this.g2 = (Graphics2D) g;
-		this.g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+    private void render(Graphics g) {
+        Graphics2D g2 = (Graphics2D) g;
+        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
 
 		// Render Background
-		this.g2.setColor(Color.WHITE);
-		this.g2.fillRect(0, 0, getWidth(), getHeight());
+        g2.setColor(Color.WHITE);
+        g2.fillRect(0, 0, getWidth(), getHeight());
 
 		bodies = hCController.getBodies();
 		// Render Objects
 		for (int i = 0; i < subCount; i++) {
-			bodyNr = bodies.get(i).getId();
-			switch (comboChoice) {
+            int bodyNr = bodies.get(i).getId();
+            String info;
+            switch (comboChoice) {
 			case 0:
 				info = "" + bodyNr;
 				break;
@@ -188,34 +152,34 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 				info = "" + subnets.get(bodyNr).getSwitches().size();
 				break;
 			case 4:
-				info = "" + hCController.getTotalProduction(new ArrayList<AbstractCpsObject>(subnets.get(bodyNr).getObjects()));
-				break;
+                info = "" + hCController.getTotalProduction(new ArrayList<>(subnets.get(bodyNr).getObjects()));
+                break;
 			case 5:
-				info = "" + hCController.getTotalConsumption(new ArrayList<AbstractCpsObject>(subnets.get(bodyNr).getObjects()));
-				break;
+                info = "" + hCController.getTotalConsumption(new ArrayList<>(subnets.get(bodyNr).getObjects()));
+                break;
 			case 6:
-				info = "" + hCController.getTotalElements(new ArrayList<AbstractCpsObject>(subnets.get(bodyNr).getObjects()));
-				break;
+                info = "" + hCController.getTotalElements(new ArrayList<>(subnets.get(bodyNr).getObjects()));
+                break;
 			case 7:
-				info = "" + hCController.getTotalProducers(new ArrayList<AbstractCpsObject>(subnets.get(bodyNr).getObjects()));
-				break;
+                info = "" + hCController.getTotalProducers(new ArrayList<>(subnets.get(bodyNr).getObjects()));
+                break;
 			case 8:
-				info = "" + hCController.getActiveElements(new ArrayList<AbstractCpsObject>(subnets.get(bodyNr).getObjects()));
-				break;
+                info = "" + hCController.getActiveElements(new ArrayList<>(subnets.get(bodyNr).getObjects()));
+                break;
 			default:
 				info = "" + bodyNr;
 				break;
 			}
 			bodies.get(i).setRadius((subnets.get(bodies.get(i).getId()).getObjects().size() * 5 + 10)
 					* controller.getHolonBodyScale() / 100);
-			bodies.get(i).draw(this.g2, info);
-		}
+            bodies.get(i).draw(g2, info);
+        }
 	}
 
 	
 	// calc the center of the canvas
-	public void calcCenter() {
-		center = this.getSize();
+    private void calcCenter() {
+        center = this.getSize();
 		center.height /= 2;
 		center.width /= 2;
 	}
@@ -227,19 +191,16 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 
 	@Override
 	public void mouseClicked(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseEntered(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseExited(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
@@ -279,6 +240,5 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 
 	@Override
 	public void mouseMoved(MouseEvent e) {
-		// TODO Auto-generated method stub
 	}
 }

+ 15 - 20
src/ui/view/Main.java

@@ -1,11 +1,10 @@
 package ui.view;
 
-import java.awt.EventQueue;
-import javax.swing.UIManager;
-import javax.swing.UnsupportedLookAndFeelException;
+import ui.controller.Control;
+import ui.model.Model;
 
-import ui.controller.*;
-import ui.model.*;
+import javax.swing.*;
+import java.awt.*;
 
 /**
  * The main Class in this Program. The GUI is created in this Class.
@@ -28,7 +27,6 @@ public class Main {
 			try {
 			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
 			} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
-			// TODO Auto-generated catch block
 			e.printStackTrace();
 			}
 		else
@@ -36,24 +34,21 @@ public class Main {
 				UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
 			} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
 					| UnsupportedLookAndFeelException e) {
-				// TODO Auto-generated catch block
 				e.printStackTrace();
 			}
 
-		EventQueue.invokeLater(new Runnable() {
-			public void run() {
-				try {
-					Model model = new Model();
-					Control control = new Control(model);
-					GUI view = new GUI(control);
+        EventQueue.invokeLater(() -> {
+            try {
+                Model model = new Model();
+                Control control = new Control(model);
+                GUI view = new GUI(control);
 
-					view.getFrmCyberPhysical().setVisible(true);
+                view.getFrmCyberPhysical().setVisible(true);
 
-				} catch (Exception e) {
-					e.printStackTrace();
-				}
-			}
-		});
-	}
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        });
+    }
 
 }

+ 25 - 34
src/ui/view/StatisticGraphPanel.java

@@ -19,26 +19,15 @@ public class StatisticGraphPanel extends JSplitPane {
 
     private static final long serialVersionUID = 1L;
 
-    // Model/Controller
-//    private Model model;
-//    private Control controller;
-    private final JLabel graphNameLabel;
     private final JLabel maximumLabel = new JLabel("0");
     private final JPanel legendPanel = new JPanel();
-    String[] backgroundColors = {"White", "Dark", "Red", "Blue"};
+    private String[] backgroundColors = {"White", "Dark", "Red", "Blue"};
     // Variables
-    String graphName;
+    private String graphName;
     // Components
     private StatisticGraph sGraph;
-    private JPanel topPanel = new JPanel();
-    private JButton closeButton = new JButton("X");
-    private JPanel graphOptionsContainer = new JPanel();
     private JToggleButton toggleGridButton = new JToggleButton("Hide Grid");
-    private JLabel backgroundColorLabel = new JLabel("Background: ");
     private JComboBox backgroundColorSelector = new JComboBox(backgroundColors);
-    private JButton savImgButton = new JButton("Save as Image");
-    private JPanel topContainer = new JPanel();
-    private JPanel buttomContainer = new JPanel();
     private JSplitPane that;
     private Hashtable<String, StatisticGraphPanel> graphHashtable;
 
@@ -48,7 +37,7 @@ public class StatisticGraphPanel extends JSplitPane {
      * @param mod  the Model
      * @param cont the Controller
      */
-    public StatisticGraphPanel(Model mod, Control cont, String name, Hashtable<String, StatisticGraphPanel> gHt) {
+    StatisticGraphPanel(Model mod, Control cont, String name, Hashtable<String, StatisticGraphPanel> gHt) {
         super();
         setDividerSize(0);
         setPreferredSize(new Dimension(600, 300));
@@ -61,7 +50,9 @@ public class StatisticGraphPanel extends JSplitPane {
         this.sGraph = new StatisticGraph(mod, cont);
         this.graphName = name;
         this.graphHashtable = gHt;
+        JPanel topContainer = new JPanel();
         topContainer.setLayout(new BorderLayout(0, 0));
+        JPanel buttomContainer = new JPanel();
         buttomContainer.setPreferredSize(new Dimension(0, 0));
         buttomContainer.setMinimumSize(new Dimension(0, 0));
         buttomContainer.setAlignmentX(Component.LEFT_ALIGNMENT);
@@ -76,7 +67,7 @@ public class StatisticGraphPanel extends JSplitPane {
         sGraph.setMinimumSize(new Dimension(100, 150));
 
         // Graph Name
-        graphNameLabel = new JLabel(graphName);
+        JLabel graphNameLabel = new JLabel(graphName);
         graphNameLabel.setHorizontalTextPosition(JLabel.CENTER);
         // set font bold and font size slightly bigger than the rest
         graphNameLabel.setFont(new Font(graphNameLabel.getFont().getName(), Font.BOLD, 14));
@@ -93,19 +84,24 @@ public class StatisticGraphPanel extends JSplitPane {
         });
 
         // Panel on top (Name and Close Button)
+        JPanel topPanel = new JPanel();
         topPanel.setLayout(new BorderLayout(0, 0));
         JPanel topPanelHelp = new JPanel(new BorderLayout(0, 0));
         topPanelHelp.add(graphNameLabel, BorderLayout.CENTER);
         // graph options
+        JPanel graphOptionsContainer = new JPanel();
         graphOptionsContainer.add(toggleGridButton);
         graphOptionsContainer.add(new JLabel("  "));    // spacer
+        JLabel backgroundColorLabel = new JLabel("Background: ");
         graphOptionsContainer.add(backgroundColorLabel);
         graphOptionsContainer.add(backgroundColorSelector);
         graphOptionsContainer.add(new JLabel("  "));    // spacer
+        JButton savImgButton = new JButton("Save as Image");
         graphOptionsContainer.add(savImgButton);
         topPanelHelp.add(graphOptionsContainer, BorderLayout.EAST);
         //
         topPanel.add(topPanelHelp, BorderLayout.CENTER);
+        JButton closeButton = new JButton("X");
         topPanel.add(closeButton, BorderLayout.EAST);
         savImgButton.addActionListener(actionEvent -> {
             BufferedImage img = new BufferedImage(that.getWidth(), that.getHeight(), BufferedImage.TYPE_INT_RGB);
@@ -117,7 +113,6 @@ public class StatisticGraphPanel extends JSplitPane {
                     ImageIO.write(img, "jpg", new File(file + ".jpg"));
                 }
             } catch (IOException e1) {
-                // TODO Auto-generated catch block
                 e1.printStackTrace();
             }
 
@@ -180,8 +175,6 @@ public class StatisticGraphPanel extends JSplitPane {
 
     /**
      * Adds the Set to the Graph.
-     *
-     * @param set
      */
 
     public void addObject(TrackedDataSet set) {
@@ -301,33 +294,31 @@ public class StatisticGraphPanel extends JSplitPane {
 
     /**
      * Set the Maximum Label
-     *
-     * @param max
      */
-    public void setMaximumLabel(double max) {
+    void setMaximumLabel(double max) {
         maximumLabel.setText(Double.toString(max));
     }
 
-    /**
-     * Get the name of the Graph.
-     *
-     * @return the name of the Graph
-     */
-    public String getGraphName() {
-        return this.graphName;
-    }
+//    /**
+//     * Get the name of the Graph.
+//     *
+//     * @return the name of the Graph
+//     */
+//    public String getGraphName() {
+//        return this.graphName;
+//    }
 
     /**
      * Calls the addValue function of the sGraph
      */
-    public void addValues() {
+    void addValues() {
         sGraph.addValues();
     }
 
     /**
      * Calls the calcMaximum function of the sGraph
      */
-    public void calcMaximum() {
+    void calcMaximum() {
         sGraph.calcMaximum();
     }
 
@@ -335,9 +326,9 @@ public class StatisticGraphPanel extends JSplitPane {
         return sGraph;
     }
 
-    public void setStatisticGraph(StatisticGraph sG) {
-        this.sGraph = sG;
-    }
+//    public void setStatisticGraph(StatisticGraph sG) {
+//        this.sGraph = sG;
+//    }
 
     /**
      * Reset the Graph. Delete all calculated values.

+ 11 - 22
src/ui/view/StatisticsTab.java

@@ -1,67 +1,56 @@
 package ui.view;
 
-import java.awt.Image;
+import javax.swing.*;
 import java.awt.event.MouseEvent;
 import java.awt.event.MouseListener;
 import java.awt.event.MouseMotionListener;
-import javax.swing.JPanel;
-
-import ui.controller.Control;
-import ui.model.Model;
 
 public class StatisticsTab extends JPanel implements MouseListener, MouseMotionListener {
 
 	private static final long serialVersionUID = 1L;
-	private Image img = null;
-	private int x = 0;
-	private int y = 0;
-	private Model model;
-	private final Control controller;
-
-	public StatisticsTab(Model mod, Control control) {
-		this.model = mod;
-		this.controller = control;
-	}
+//	private Image img = null;
+//	private int x = 0;
+//	private int y = 0;
+//	private Model model;
+//	private final Control controller;
+
+//	public StatisticsTab(Model mod, Control control) {
+//		this.model = mod;
+//		this.controller = control;
+//	}
 
 	@Override
 	public void mouseDragged(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseMoved(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseClicked(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mousePressed(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseReleased(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseEntered(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseExited(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}