Browse Source

Major changes in StoreController

Teh-Hai Julian Zheng 8 years ago
parent
commit
020663214a

+ 24 - 1
src/TypeAdapter/ColorAdapter.java

@@ -1,5 +1,28 @@
 package TypeAdapter;
 
-public class ColorAdapter {
+import java.awt.Color;
+import java.lang.reflect.Type;
+
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+
+public class ColorAdapter implements JsonSerializer<Color>, JsonDeserializer<Color> {
+
+	@Override
+	public Color deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
+		// TODO Auto-generated method stub
+		return new Color(arg0.getAsInt());
+	}
+
+	@Override
+	public JsonElement serialize(Color arg0, Type arg1, JsonSerializationContext arg2) {
+		// TODO Auto-generated method stub
+		return new JsonPrimitive(Integer.toHexString(arg0.getRGB()));
+	}
 
 }

+ 0 - 45
src/TypeAdapter/CpsEdgeAdapter.java

@@ -1,45 +0,0 @@
-package TypeAdapter;
-
-import java.lang.reflect.Type;
-
-import com.google.gson.JsonDeserializationContext;
-import com.google.gson.JsonDeserializer;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import com.google.gson.JsonPrimitive;
-import com.google.gson.JsonSerializationContext;
-import com.google.gson.JsonSerializer;
-
-import classes.CpsEdge;
-
-public class CpsEdgeAdapter implements JsonSerializer<CpsEdge>, JsonDeserializer<CpsEdge> {
-
-	@Override
-	public JsonElement serialize(CpsEdge arg0, Type arg1, JsonSerializationContext arg2) {
-		// TODO Auto-generated method stub
-		JsonObject object = new JsonObject();
-		object.add("type", new JsonPrimitive(arg0.getClass().getSimpleName()));
-		object.add("properties", arg2.serialize(arg0, arg0.getClass()));
-		object.add("a", new JsonPrimitive(arg0.getA().getID()));
-		object.add("b", new JsonPrimitive(arg0.getB().getID()));
-		
-		return object;
-	}
-
-	@Override
-	public CpsEdge deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
-		// TODO Auto-generated method stub
-		JsonObject object = arg0.getAsJsonObject();
-		String type = object.get("type").getAsString();
-		JsonElement element = object.get("properties");
-		try {
-			String packageName = "classes.";
-			return arg2.deserialize(element, Class.forName(packageName + type));
-		} catch (ClassNotFoundException cnfe) {
-			// TODO: handle exception
-			throw new JsonParseException("Unknown element type: " + type, cnfe);
-		}
-	}
-
-}

+ 1 - 0
src/classes/CpsEdge.java

@@ -39,6 +39,7 @@ public class CpsEdge {
 	@Expose
 	int isConnected;
 	// for internal use --> flow of electricity (simulation state)
+	
 	ArrayList<Integer> tags;
 	// for internal use --> flow of electricity (simulation state)
 	ArrayList<Integer> pseudoTags;

+ 1 - 1
src/tests/PraktikumHolonsTestLoadAndStoreController.java

@@ -80,7 +80,7 @@ public class PraktikumHolonsTestLoadAndStoreController {
 			assertTrue("Save File was not created", new File(path + "TestSavMinimal.json").exists());
 
 			File cat = new File(path + "TestCategoryMinimal.json");
-			storeController.writeCategoryFile(cat.getAbsolutePath());
+			//storeController.writeCategoryFile(cat.getAbsolutePath());
 			assertTrue("Category File was not created", new File(path + "TestCategoryMinimal.json").exists());
 
 			File canvas = new File(path + "TestCanvasMinimal.json");

+ 218 - 61
src/ui/controller/StoreController.java

@@ -1,8 +1,10 @@
 package ui.controller;
 
+import java.awt.Color;
 import java.awt.Point;
 import java.io.FileWriter;
 import java.io.IOException;
+import java.util.ArrayList;
 import java.util.ListIterator;
 
 import org.json.simple.JSONArray;
@@ -12,11 +14,17 @@ import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.stream.JsonWriter;
 
 import TypeAdapter.AbstractCpsObjectAdapter;
+import TypeAdapter.ColorAdapter;
 import TypeAdapter.CpsEdgeAdapter;
+
+import TypeAdapter.PositionAdapter;
 import classes.Category;
 import classes.CpsEdge;
+import classes.CpsUpperNode;
 import classes.AbstractCpsObject;
 import classes.HolonElement;
 import classes.HolonObject;
@@ -24,6 +32,7 @@ import classes.HolonSwitch;
 import classes.HolonTransformer;
 import classes.IdCounter;
 import classes.Position;
+import sun.misc.Queue;
 import ui.model.Model;
 
 /**
@@ -33,7 +42,24 @@ import ui.model.Model;
  */
 public class StoreController {
 
+	public enum MODE {
+		COMPLETE, PARTIAL
+	}
+
+	public enum TYPE {
+		CATEGORY, CANVAS
+	}
+
+	public enum EDGETYPE {
+		CANVAS, CONNECTION, NODE, OLD
+	}
+
+	public enum NUMTYPE {
+		CATEGORY, OBJECT, ELEMENT, EDGE, CONNECTION, NODEEDGE, OLDEDGE
+	}
+
 	private Model model;
+	private int nCat, nObj, nEle, nEdge, nConn, nNodeEdge, nOldEdge;
 
 	/**
 	 * Constructor.
@@ -43,7 +69,7 @@ public class StoreController {
 	 */
 	public StoreController(Model model) {
 		this.model = model;
-
+		initNumeration();
 	}
 
 	/**
@@ -58,38 +84,43 @@ public class StoreController {
 	 */
 	public void writeSaveFile(String path) throws IOException {
 
+		// instance of the builder and give the wanted options
 		GsonBuilder builder = new GsonBuilder();
-		builder.registerTypeAdapter(AbstractCpsObject.class, new AbstractCpsObjectAdapter())
-				.registerTypeAdapter(CpsEdge.class, new CpsEdgeAdapter()).serializeNulls()
-				.excludeFieldsWithoutExposeAnnotation().setPrettyPrinting();
+		builder.excludeFieldsWithoutExposeAnnotation().serializeNulls();
+		builder.registerTypeAdapter(AbstractCpsObject.class, new AbstractCpsObjectAdapter());
+		builder.registerTypeAdapter(Position.class, new PositionAdapter());
+		builder.registerTypeAdapter(Color.class, new ColorAdapter());
+		// use the builder and make a instance of the Gson
 		Gson gson = builder.create();
 
-		JSONObject json = new JSONObject();
+		JsonObject file = new JsonObject();
 
-		// json.put("MODE", "ALL");
-		// json.put("ID", IdCounter.getCounter());
-		// json.put("SIZEX", model.getCanvasX());
-		// json.put("SIZEY", model.getCanvasY());
-		// writeCategory(gson, json);
-		// writeCategoryObjects(gson, json);
+		initialize(MODE.COMPLETE, file);
+		storeCategory(gson, file);
+		storeCanvas(gson, file);
+		System.out.println(file.toString());
 		// writeCanvasObjects(json);
 		// writeCategoryElements(json);
 		// writeCanvasElements(json);
 		// writeEdges(json);
 		// writeElementGraph(json);
 		int i = 1;
-//		for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
-//			String k = gson.toJson(cps, AbstractCpsObject.class);
-//			System.out.println(k);
-//		}
-
-		for (CpsEdge edge : model.getEdgesOnCanvas()) {
-			String k = gson.toJson(edge);
-			System.out.println(k);
-		}
+		// for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
+		// String k = objectGson.toJson(cps, AbstractCpsObject.class);
+		// System.out.println(k);
+		// }
+
+		// for (CpsEdge edge : model.getEdgesOnCanvas()) {
+		//
+		// JsonObject k = new JsonObject();
+		// k.add("Edge", objectGson.toJsonTree(edge));
+		// k.add("a", new JsonPrimitive(edge.getA().getID()));
+		// k.add("b", new JsonPrimitive(edge.getB().getID()));
+		// System.out.println(k);
+		// }
 
 		FileWriter writer = new FileWriter(path);
-		writer.write(json.toJSONString());
+		// writer.write(json.toJSONString());
 		getClass();
 
 		writer.flush();
@@ -97,49 +128,110 @@ public class StoreController {
 	}
 
 	/**
-	 * Write the Canvas File.
+	 * Write needed default parameter into the JsonObject. Can be extended later
+	 * on
 	 * 
-	 * @param path
-	 *            the Path
-	 * @throws IOException
-	 *             Exception
+	 * @param mode
+	 * @param file
 	 */
-	public void writeCanvasFile(String path) throws IOException {
+	private void initialize(MODE mode, JsonObject file) {
+		// TODO Auto-generated method stub
+		switch (mode) {
+		case COMPLETE:
+			file.add("MODE", new JsonPrimitive(mode.name()));
+			file.add("IDCounter", new JsonPrimitive(IdCounter.getCounter()));
+			file.add("CANVAS_SIZE_X", new JsonPrimitive(model.getCanvasX()));
+			file.add("CANVAS_SIZE_Y", new JsonPrimitive(model.getCanvasY()));
+			break;
+		case PARTIAL:
+			file.add("MODE", new JsonPrimitive(mode.name()));
+			file.add("IDCounter", new JsonPrimitive(IdCounter.getCounter()));
+			break;
+
+		default:
+			break;
+		}
+	}
 
-		JSONObject json = new JSONObject();
+	/**
+	 * Store all Categories and Object into a Json File via Serialization
+	 * 
+	 * @param gson
+	 * @param file
+	 */
+	private void storeCategory(Gson gson, JsonObject file) {
+		// TODO Auto-generated method stub
+		for (Category cat : model.getCategories()) {
+			String key = "CATEGORY" + getNumerator(NUMTYPE.CATEGORY);
+			file.add(key, new JsonPrimitive(cat.getName()));
+			for (AbstractCpsObject obj : cat.getObjects()) {
+				file.add("CATEGORY.OBJECT" + getNumerator(NUMTYPE.OBJECT),
+						new JsonPrimitive(gson.toJson(obj, AbstractCpsObject.class)));
+				if (obj instanceof HolonObject)
+					elementsToJson(TYPE.CATEGORY, gson, file, obj);
+			}
+		}
+	}
 
-		json.put("MODE", "CANVAS");
-		json.put("ID", IdCounter.getCounter());
-		writeCanvasObjects(json);
-		writeCanvasElements(json);
-		writeEdges(json);
-		writeElementGraph(json);
+	/**
+	 * 
+	 * @param gson
+	 * @param file
+	 */
+	private void storeCanvas(Gson gson, JsonObject file) {
+		// TODO Auto-generated method stub
+		Queue<AbstractCpsObject> queue = new Queue<>();
+		AbstractCpsObject u = null;
 
-		FileWriter writer = new FileWriter(path);
-		writer.write(json.toJSONString());
-		getClass();
+		edgeToJson(EDGETYPE.CANVAS, gson, file, 0, model.getEdgesOnCanvas());
+
+		for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
+			queue.enqueue(cps);
+		}
+
+		while (!queue.isEmpty()) {
+			try {
+				u = queue.dequeue();
+			} catch (InterruptedException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+			String key = "CANVAS.OBJECT" + getNumerator(NUMTYPE.OBJECT);
+			file.add(key, new JsonPrimitive(gson.toJson(u, AbstractCpsObject.class)));
+			edgeToJson(EDGETYPE.CONNECTION, gson, file, u.getID(), u.getConnections());
+
+			if (u instanceof HolonObject)
+				elementsToJson(TYPE.CANVAS, gson, file, u);
+			if (u instanceof CpsUpperNode) {
+				for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
+					queue.enqueue(adjacent);
+
+				}
+				edgeToJson(EDGETYPE.NODE, gson, file, u.getID(), ((CpsUpperNode) u).getNodeEdges());
+				edgeToJson(EDGETYPE.OLD, gson, file, u.getID(), ((CpsUpperNode) u).getOldEdges());
+			}
+		}
 
-		writer.flush();
-		writer.close();
 	}
 
 	/**
-	 * Write the Category File.
+	 * Write the Canvas File.
 	 * 
 	 * @param path
 	 *            the Path
 	 * @throws IOException
-	 *             exception
+	 *             Exception
 	 */
-	public void writeCategoryFile(String path) throws IOException {
+	public void writeCanvasFile(String path) throws IOException {
 
 		JSONObject json = new JSONObject();
 
-		json.put("MODE", "CATEGORY");
-		// eventuell muss man ID auch Speichern
-		// writeCategory(gson, json);
-		// writeCategoryObjects(gson, json);
-		writeCategoryElements(json);
+		json.put("MODE", "CANVAS");
+		json.put("ID", IdCounter.getCounter());
+		writeCanvasObjects(json);
+		writeCanvasElements(json);
+		writeEdges(json);
+		writeElementGraph(json);
 
 		FileWriter writer = new FileWriter(path);
 		writer.write(json.toJSONString());
@@ -199,7 +291,7 @@ public class StoreController {
 		JSONArray arr = new JSONArray();
 		int i = 1;
 		for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
-			arr.add(getObjectType(cps));
+			// arr.add(getObjectType(cps));
 			arr.add(cps.getObjName());
 			arr.add(cps.getName());
 			arr.add(cps.getID());
@@ -336,22 +428,87 @@ public class StoreController {
 		}
 	}
 
+	private void elementsToJson(TYPE type, Gson gson, JsonObject file, AbstractCpsObject obj) {
+		// TODO Auto-generated method stub
+		JsonObject temp = new JsonObject();
+		
+		for (HolonElement ele : ((HolonObject) obj).getElements()) {
+			file.add(type.name() + ".OBJECT.ELEMENT" + +getNumerator(NUMTYPE.ELEMENT),
+					new JsonPrimitive(gson.toJson(ele)));
+		}
+
+	}
+
+	private void edgeToJson(EDGETYPE type, Gson gson, JsonObject file, int id, ArrayList<CpsEdge> arr) {
+		// TODO Auto-generated method stub
+		String k = null;
+		int i = 0;
+		JsonObject temp = new JsonObject();
+
+		for (CpsEdge edge : arr) {
+
+			temp.add("properties", new JsonPrimitive(gson.toJson(edge)));
+			temp.add("A", new JsonPrimitive(edge.getA().getID()));
+			temp.add("B", new JsonPrimitive(edge.getB().getID()));
+
+			switch (type) {
+			case CANVAS:
+				k = "CANVAS.EDGE" + getNumerator(NUMTYPE.EDGE);
+				break;
+			case CONNECTION:
+				k = "CANVAS.OBJECT.CONNECTION" + getNumerator(NUMTYPE.CONNECTION);
+				break;
+			case NODE:
+				k = "CANVAS.UPPERNODE.EDGE" + getNumerator(NUMTYPE.NODEEDGE);
+				temp.add("ID", new JsonPrimitive(id));
+				break;
+			case OLD:
+				k = "CANVAS.UPPERNODE.OLD" + getNumerator(NUMTYPE.OLDEDGE);
+				temp.add("ID", new JsonPrimitive(id));
+				break;
+			default:
+				break;
+			}
+
+			file.add(k, gson.toJsonTree(temp));
+			temp = new JsonObject();
+		}
+
+	}
+
 	/**
-	 * Return the Object Type.
 	 * 
-	 * @param cps
-	 *            AbstractCpsObject
-	 * @return The Object Type
+	 * @param type
+	 * @return
+	 */
+	private int getNumerator(NUMTYPE type) {
+
+		switch (type) {
+		case CATEGORY:
+			return nCat++;
+		case OBJECT:
+			return nObj++;
+		case ELEMENT:
+			return nEle++;
+		case EDGE:
+			return nEdge++;
+		case CONNECTION:
+			return nConn++;
+		case NODEEDGE:
+			return nNodeEdge++;
+		case OLDEDGE:
+			return nOldEdge++;
+		default:
+			break;
+		}
+		return -1;
+	}
+
+	/**
+	 * Just initialize the Numerators for the Json Keys. Maybe bad Style..
 	 */
-	public String getObjectType(AbstractCpsObject cps) {
-		if (cps instanceof HolonObject)
-			return "HolonObject";
-		if (cps instanceof HolonTransformer)
-			return "HolonTransformer";
-		if (cps instanceof HolonSwitch)
-			return "HolonSwitch";
-		else
-			return "CpsNode";
+	private void initNumeration() {
+		this.nCat = this.nObj = this.nEle = this.nEdge = this.nConn = this.nNodeEdge = this.nOldEdge = 0;
 	}
 
 }