StoreController.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. package ui.controller;
  2. import java.awt.Color;
  3. import java.awt.Point;
  4. import java.awt.image.BufferedImage;
  5. import java.awt.image.DataBufferByte;
  6. import java.awt.image.WritableRaster;
  7. import java.io.File;
  8. import java.io.FileWriter;
  9. import java.io.IOException;
  10. import java.nio.file.FileSystems;
  11. import java.nio.file.Files;
  12. import java.nio.file.Path;
  13. import java.nio.file.Paths;
  14. import java.util.ArrayDeque;
  15. import java.util.ArrayList;
  16. import java.util.LinkedList;
  17. import java.util.List;
  18. import javax.imageio.ImageIO;
  19. import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
  20. import com.google.gson.Gson;
  21. import com.google.gson.GsonBuilder;
  22. import com.google.gson.JsonObject;
  23. import com.google.gson.JsonPrimitive;
  24. import com.sun.corba.se.spi.ior.Writeable;
  25. import TypeAdapter.AbstractCpsObjectAdapter;
  26. import TypeAdapter.ColorAdapter;
  27. import TypeAdapter.ImageAdapter;
  28. import TypeAdapter.PositionAdapter;
  29. import classes.Category;
  30. import classes.CpsEdge;
  31. import classes.CpsUpperNode;
  32. import classes.AbstractCpsObject;
  33. import classes.HolonElement;
  34. import classes.HolonObject;
  35. import classes.HolonSwitch;
  36. import classes.IdCounter;
  37. import classes.IdCounterElem;
  38. import classes.Position;
  39. import ui.model.Model;
  40. /**
  41. * Controller for Storage.
  42. *
  43. * @author Gruppe14
  44. */
  45. public class StoreController {
  46. public enum MODE {
  47. COMPLETE, PARTIAL
  48. }
  49. public enum TYPE {
  50. CATEGORY, CANVAS
  51. }
  52. public enum EDGETYPE {
  53. CANVAS, CONNECTION, NODE, OLD, LAYER
  54. }
  55. public enum NUMTYPE {
  56. CATEGORY, OBJECT, ELEMENT, EDGE, CONNECTION, NODEEDGE, OLDEDGE, UNITGRAPH, IMAGE
  57. }
  58. public enum GRAPHTYPE {
  59. SWITCH, ELEMENT
  60. }
  61. private Model model;
  62. private Gson gson;
  63. private int nCat, nObj, nEle, nEdge, nConn, nNodeEdge, nOldEdge, nUnitGraph, nImg;
  64. /**
  65. * Constructor.
  66. *
  67. * @param model
  68. * the Model
  69. */
  70. public StoreController(Model model) {
  71. this.model = model;
  72. initGson();
  73. }
  74. /**
  75. * Writes the current State of the Modelling into a JSON File which can be
  76. * loaded.
  77. *
  78. * @param path
  79. * the Path
  80. *
  81. * @throws IOException
  82. * exception
  83. */
  84. public void writeSaveFile(String path) throws IOException {
  85. initNumeration();
  86. JsonObject file = new JsonObject();
  87. initialize(MODE.COMPLETE, file);
  88. storeCategory(file);
  89. storeCanvas(file);
  90. FileWriter writer = new FileWriter(path);
  91. writer.write(gson.toJson(file));
  92. writer.flush();
  93. writer.close();
  94. }
  95. /**
  96. * Writes the Autosave File.
  97. *
  98. * @param path
  99. * the Path
  100. * @throws IOException
  101. * Exception
  102. */
  103. public void writeAutosaveFile(String path) throws IOException {
  104. initNumeration();
  105. JsonObject file = new JsonObject();
  106. initialize(MODE.PARTIAL, file);
  107. storeCanvas(file);
  108. FileWriter writer = new FileWriter(path);
  109. writer.write(gson.toJson(file));
  110. writer.flush();
  111. writer.close();
  112. }
  113. /**
  114. * Write needed default parameter into the JsonObject. Can be extended later
  115. * on
  116. *
  117. * @param mode
  118. * @param file
  119. */
  120. private void initialize(MODE mode, JsonObject file) {
  121. // TODO Auto-generated method stub
  122. switch (mode) {
  123. case COMPLETE:
  124. file.add("MODE", new JsonPrimitive(mode.name()));
  125. file.add("IDCOUNTER", new JsonPrimitive(IdCounter.getCounter()));
  126. file.add("IDCOUNTERELEMENT", new JsonPrimitive(IdCounterElem.getCounter()));
  127. file.add("CANVAS_SIZE_X", new JsonPrimitive(model.getCanvasX()));
  128. file.add("CANVAS_SIZE_Y", new JsonPrimitive(model.getCanvasY()));
  129. break;
  130. case PARTIAL:
  131. file.add("MODE", new JsonPrimitive(mode.name()));
  132. file.add("IDCOUNTER", new JsonPrimitive(IdCounter.getCounter()));
  133. file.add("IDCOUNTERELEMENT", new JsonPrimitive(IdCounterElem.getCounter()));
  134. break;
  135. default:
  136. break;
  137. }
  138. }
  139. /**
  140. * Store all Categories and Object into a Json File via Serialization
  141. *
  142. * @param file
  143. */
  144. private void storeCategory(JsonObject file) {
  145. // TODO Auto-generated method stub
  146. // forall categories store them into the jsontree
  147. for (Category cat : model.getCategories()) {
  148. String key = "CATEGORY" + getNumerator(NUMTYPE.CATEGORY);
  149. file.add(key, new JsonPrimitive(cat.getName()));
  150. // forall object in the category store them into the jsontree
  151. for (AbstractCpsObject obj : cat.getObjects()) {
  152. file.add("CGOBJECT" + getNumerator(NUMTYPE.OBJECT), gson.toJsonTree(obj, AbstractCpsObject.class));
  153. // if its a holonobject add elements too
  154. if (obj instanceof HolonObject)
  155. elementsToJson(TYPE.CATEGORY, file, obj);
  156. }
  157. }
  158. }
  159. /**
  160. * Travers through all Objects via BFS and Stores everything relevant
  161. *
  162. * @param file
  163. */
  164. private void storeCanvas(JsonObject file) {
  165. // TODO Auto-generated method stub
  166. ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
  167. AbstractCpsObject u = null;
  168. // put all objects into queue since there is not starting object
  169. for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
  170. queue.add(cps);
  171. }
  172. // while quene not empty
  173. while (!queue.isEmpty()) {
  174. // u = current node
  175. u = queue.pop();
  176. // add currentnode into jsontree
  177. String key = "CVSOBJECT" + getNumerator(NUMTYPE.OBJECT);
  178. file.add(key, gson.toJsonTree(u, AbstractCpsObject.class));
  179. // and its connections too
  180. edgeToJson(EDGETYPE.CONNECTION, file, u.getId(), u.getConnections());
  181. // if holonobject elements too
  182. if (u instanceof HolonObject)
  183. elementsToJson(TYPE.CANVAS, file, u);
  184. // if switch graphpoints too
  185. if (u instanceof HolonSwitch)
  186. if (((HolonSwitch) u).getGraphPoints().size() != 0)
  187. unitgraphToJson(GRAPHTYPE.SWITCH, file, u.getId(), ((HolonSwitch) u).getGraphPoints());
  188. // if uppernode put all nodes inside the uppernode into queue
  189. if (u instanceof CpsUpperNode) {
  190. for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
  191. queue.add(adjacent);
  192. }
  193. // dont forget to add the nodeedges and oldedges
  194. edgeToJson(EDGETYPE.NODE, file, u.getId(), ((CpsUpperNode) u).getNodeEdges());
  195. edgeToJson(EDGETYPE.OLD, file, u.getId(), ((CpsUpperNode) u).getOldEdges());
  196. }
  197. }
  198. // lastly add canvasedges into json
  199. edgeToJson(EDGETYPE.CANVAS, file, 0, model.getEdgesOnCanvas());
  200. }
  201. /**
  202. * Stores Category or Canvas Elements into Json
  203. *
  204. * @param type
  205. * @param gson
  206. * @param file
  207. * @param obj
  208. */
  209. public void elementsToJson(TYPE type, JsonObject file, AbstractCpsObject obj) {
  210. // TODO Auto-generated method stub
  211. JsonObject temp = new JsonObject();
  212. String key = null;
  213. // forall elements store them into json and include the id of the object
  214. for (HolonElement ele : ((HolonObject) obj).getElements()) {
  215. temp.add("properties", gson.toJsonTree(ele));
  216. temp.add("ID", new JsonPrimitive(obj.getId()));
  217. // switch for deciding the key
  218. switch (type) {
  219. case CANVAS:
  220. key = "CVSELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  221. break;
  222. case CATEGORY:
  223. key = "CGELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  224. break;
  225. default:
  226. break;
  227. }
  228. file.add(key, gson.toJsonTree(temp));
  229. // if there are gps add them into
  230. if (ele.getGraphPoints().size() != 0)
  231. unitgraphToJson(GRAPHTYPE.ELEMENT, file, ele.getId(), ele.getGraphPoints());
  232. temp = new JsonObject();
  233. }
  234. }
  235. /**
  236. * Put the UnitGraphs of Switches or Elements into Json
  237. *
  238. * @param ele
  239. */
  240. public void unitgraphToJson(GRAPHTYPE type, JsonObject file, int id, LinkedList<Point> graph) {
  241. JsonObject temp = new JsonObject();
  242. String key = null;
  243. // forall points add them
  244. for (int i = 0; i < graph.size(); i++) {
  245. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  246. }
  247. // decide key
  248. switch (type) {
  249. case SWITCH:
  250. key = "SWUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  251. break;
  252. case ELEMENT:
  253. key = "ELEUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  254. break;
  255. default:
  256. break;
  257. }
  258. // add id of element so it can be found again
  259. temp.add("ID", new JsonPrimitive(id));
  260. file.add(key, gson.toJsonTree(temp));
  261. }
  262. /**
  263. * Canvas-Edge, Connections, Node-Edge and Old-Edges to json
  264. *
  265. * @param type
  266. * @param file
  267. * @param id
  268. * @param arr
  269. */
  270. public void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
  271. // TODO Auto-generated method stub
  272. String k = null;
  273. boolean b = false;
  274. JsonObject temp = new JsonObject();
  275. for (CpsEdge edge : arr) {
  276. // add properties and only the ids from a and b
  277. temp.add("properties", gson.toJsonTree(edge));
  278. temp.add("A", new JsonPrimitive(edge.getA().getId()));
  279. temp.add("B", new JsonPrimitive(edge.getB().getId()));
  280. // Key and occasionally the id of Uppernode
  281. switch (type) {
  282. case CANVAS:
  283. k = "CVSEDGE" + getNumerator(NUMTYPE.EDGE);
  284. break;
  285. case CONNECTION:
  286. k = "CONNEDGE" + getNumerator(NUMTYPE.CONNECTION);
  287. break;
  288. case NODE:
  289. temp.add("ID", new JsonPrimitive(id));
  290. k = "NODEEDGE" + getNumerator(NUMTYPE.NODEEDGE);
  291. break;
  292. case OLD:
  293. temp.add("ID", new JsonPrimitive(id));
  294. k = "OLDEDGE" + getNumerator(NUMTYPE.OLDEDGE);
  295. break;
  296. default:
  297. break;
  298. }
  299. // lookup if the CVS, NODE or OLDEDGE are also connections
  300. if (edge.getA().getConnections().contains(edge) && edge.getA().getConnections().contains(edge)
  301. && !type.equals(EDGETYPE.CONNECTION))
  302. b = true;
  303. temp.add("connection", new JsonPrimitive(b));
  304. file.add(k, gson.toJsonTree(temp));
  305. temp = new JsonObject();
  306. }
  307. }
  308. private void imageToJson(JsonObject file) {
  309. // ArrayList<String> images = new ArrayList<>();
  310. // BufferedImage buffered = null;
  311. // WritableRaster raster = null;
  312. // DataBufferByte data = null;
  313. // String k = null;
  314. // JsonObject temp = new JsonObject();
  315. //
  316. // try {
  317. // Files.newDirectoryStream(Paths.get(System.getProperty("user.home") + "/HolonGUI/Images"),
  318. // p -> p.toFile().isFile()).forEach(p -> images.add(p.toString()));
  319. //
  320. // for (String str : images) {
  321. // System.out.println("aaaaa");
  322. // k = "IMAGE" + getNumerator(NUMTYPE.IMAGE);
  323. // buffered = ImageIO.read(new File(str));
  324. // raster = buffered.getRaster();
  325. // data = (DataBufferByte) raster.getDataBuffer();
  326. //
  327. // temp.add("Image", new JsonPrimitive(str.substring(str.indexOf("/HolonGUI/Images"), str.length())));
  328. // for (int i = 0; i < data.getData().length; i++) {
  329. // temp.add("" + i, new JsonPrimitive(data.getData()[i]));
  330. // System.out.println(i);
  331. // }
  332. //
  333. // file.add(k, gson.toJsonTree(temp));
  334. // }
  335. // } catch (IOException e) {
  336. // // TODO Auto-generated catch block
  337. // e.printStackTrace();
  338. // }
  339. }
  340. /**
  341. * Initialize the Gson with wanted parameters
  342. */
  343. private void initGson() {
  344. // TODO Auto-generated method stub
  345. GsonBuilder builder = new GsonBuilder();
  346. builder.excludeFieldsWithoutExposeAnnotation().serializeNulls().setPrettyPrinting();
  347. builder.registerTypeAdapter(AbstractCpsObject.class, new AbstractCpsObjectAdapter());
  348. builder.registerTypeAdapter(Position.class, new PositionAdapter());
  349. builder.registerTypeAdapter(Color.class, new ColorAdapter());
  350. // use the builder and make a instance of the Gson
  351. this.gson = builder.create();
  352. }
  353. /**
  354. * Just initialize the Numerators for the Json Keys. Maybe bad Style..
  355. */
  356. public void initNumeration() {
  357. this.nCat = this.nObj = this.nEle = this.nEdge = this.nConn = this.nNodeEdge = this.nOldEdge = this.nImg = 0;
  358. }
  359. /**
  360. * Get the wanted numerator and increment it
  361. *
  362. * @param type
  363. * @return
  364. */
  365. public int getNumerator(NUMTYPE type) {
  366. switch (type) {
  367. case CATEGORY:
  368. return nCat++;
  369. case OBJECT:
  370. return nObj++;
  371. case ELEMENT:
  372. return nEle++;
  373. case EDGE:
  374. return nEdge++;
  375. case CONNECTION:
  376. return nConn++;
  377. case NODEEDGE:
  378. return nNodeEdge++;
  379. case OLDEDGE:
  380. return nOldEdge++;
  381. case UNITGRAPH:
  382. return nUnitGraph++;
  383. case IMAGE:
  384. return nImg++;
  385. default:
  386. break;
  387. }
  388. return -1;
  389. }
  390. }