SaveController.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. package ui.controller;
  2. import classes.*;
  3. import com.google.gson.JsonObject;
  4. import com.google.gson.JsonPrimitive;
  5. import org.apache.commons.compress.archivers.ArchiveException;
  6. import org.apache.commons.compress.archivers.ArchiveOutputStream;
  7. import org.apache.commons.compress.archivers.ArchiveStreamFactory;
  8. import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
  9. import org.apache.commons.compress.utils.IOUtils;
  10. import ui.model.Model;
  11. import java.awt.*;
  12. import java.awt.geom.Point2D;
  13. import java.io.*;
  14. import java.util.*;
  15. import java.util.List;
  16. /**
  17. * Controller for Storage.
  18. *
  19. * @author Gruppe14
  20. */
  21. public class SaveController {
  22. private Model model;
  23. private int nCat, nObj, nEle, nEdge, nConn, nNodeEdge, nOldEdge, nUnitGraph, nStatsGraph;
  24. /**
  25. * Constructor.
  26. *
  27. * @param model the Model
  28. */
  29. SaveController(Model model) {
  30. this.model = model;
  31. }
  32. /**
  33. * Writes the current State of the Modelling into a JSON File which can be
  34. * loaded.
  35. *
  36. * @param path the Path
  37. * @throws IOException exception
  38. */
  39. void writeSave(String path) throws IOException, ArchiveException {
  40. File dst = new File(path);
  41. File holonFile = File.createTempFile("tmp", ".json");
  42. holonFile.deleteOnExit();
  43. dst.delete();
  44. OutputStream output = new FileOutputStream(dst);
  45. ArchiveOutputStream stream = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP,
  46. output);
  47. initNumeration();
  48. JsonObject file = new JsonObject();
  49. initialize(MODE.COMPLETE, file);
  50. storeCategory(file);
  51. storeCanvas(file);
  52. storeStatistics(file);
  53. storeData(stream);
  54. FileWriter writer = new FileWriter(holonFile);
  55. writer.write(model.getGson().toJson(file));
  56. writer.flush();
  57. writer.close();
  58. addFileToSave(holonFile, stream, false);
  59. stream.finish();
  60. output.close();
  61. }
  62. /**
  63. * Writes the windows status (its position and dimensions)
  64. *
  65. * @param path the Path where to save it
  66. */
  67. void writeWindowStatus(String path, int x, int y, int width, int height)
  68. throws IOException, ArchiveException {
  69. JsonObject file = new JsonObject();
  70. initialize(MODE.SIZE, file);
  71. storeWindowPosAndSize(file, x, y, width, height);
  72. FileWriter writer = new FileWriter(path);
  73. writer.write(model.getGson().toJson(file));
  74. writer.flush();
  75. writer.close();
  76. }
  77. /**
  78. * Writes the Autosave File.
  79. *
  80. * @param path the Path
  81. * @throws IOException Exception
  82. */
  83. void writeAutosave(String path) throws IOException {
  84. initNumeration();
  85. JsonObject file = new JsonObject();
  86. initialize(MODE.PARTIAL, file);
  87. storeCanvas(file);
  88. FileWriter writer = new FileWriter(path);
  89. writer.write(model.getGson().toJson(file));
  90. writer.flush();
  91. writer.close();
  92. }
  93. /**
  94. * Writes the Category File in Case of Changes
  95. */
  96. void writeCategory(String path) throws IOException {
  97. initNumeration();
  98. JsonObject file = new JsonObject();
  99. initialize(MODE.CATEGORY, file);
  100. storeCategory(file);
  101. FileWriter writer = new FileWriter(path);
  102. writer.write(model.getGson().toJson(file));
  103. writer.flush();
  104. writer.close();
  105. }
  106. /**
  107. * Write needed default parameter into the JsonObject. Can be extended later
  108. * on
  109. */
  110. private void initialize(MODE mode, JsonObject file) {
  111. switch (mode) {
  112. case COMPLETE:
  113. file.add("MODE", new JsonPrimitive(mode.name()));
  114. file.add("IDCOUNTER", new JsonPrimitive(IdCounter.getCounter()));
  115. file.add("IDCOUNTERELEMENT", new JsonPrimitive(IdCounterElem.getCounter()));
  116. file.add("CANVAS_SIZE_X", new JsonPrimitive(model.getCanvasX()));
  117. file.add("CANVAS_SIZE_Y", new JsonPrimitive(model.getCanvasY()));
  118. break;
  119. case PARTIAL:
  120. file.add("MODE", new JsonPrimitive(mode.name()));
  121. file.add("IDCOUNTER", new JsonPrimitive(IdCounter.getCounter()));
  122. file.add("IDCOUNTERELEMENT", new JsonPrimitive(IdCounterElem.getCounter()));
  123. file.add("CANVAS_SIZE_X", new JsonPrimitive(model.getCanvasX()));
  124. file.add("CANVAS_SIZE_Y", new JsonPrimitive(model.getCanvasY()));
  125. break;
  126. case CATEGORY:
  127. file.add("MODE", new JsonPrimitive(mode.name()));
  128. break;
  129. case SIZE:
  130. file.add("MODE", new JsonPrimitive(mode.name()));
  131. default:
  132. break;
  133. }
  134. }
  135. /**
  136. * Store all Categories and Object into a Json File via Serialization
  137. */
  138. private void storeCategory(JsonObject file) {
  139. // forall categories store them into the jsontree
  140. for (Category cat : model.getCategories()) {
  141. String key = "CATEGORY" + getNumerator(NUMTYPE.CATEGORY);
  142. file.add(key, new JsonPrimitive(cat.getName()));
  143. // forall object in the category store them into the jsontree
  144. for (AbstractCpsObject obj : cat.getObjects()) {
  145. file.add("CGOBJECT" + getNumerator(NUMTYPE.OBJECT),
  146. model.getGson().toJsonTree(obj, AbstractCpsObject.class));
  147. // if its a holonobject add elements too
  148. if (obj instanceof HolonObject)
  149. elementsToJson(TYPE.CATEGORY, file, obj);
  150. }
  151. }
  152. }
  153. private void storeWindowPosAndSize(JsonObject file, int x, int y, int width, int height) {
  154. file.add("POS_X", new JsonPrimitive(x));
  155. file.add("POS_Y", new JsonPrimitive(y));
  156. file.add("WIDTH", new JsonPrimitive(width));
  157. file.add("HEIGHT", new JsonPrimitive(height));
  158. }
  159. /**
  160. * Travers through all Objects via BFS and Stores everything relevant
  161. */
  162. private void storeCanvas(JsonObject file) {
  163. ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
  164. AbstractCpsObject u = null;
  165. // put all objects into queue since there is not starting object
  166. for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
  167. queue.add(cps);
  168. }
  169. // while quene not empty
  170. while (!queue.isEmpty()) {
  171. // u = current node
  172. u = queue.pop();
  173. // add currentnode into jsontree
  174. String key = "CVSOBJECT" + getNumerator(NUMTYPE.OBJECT);
  175. file.add(key, model.getGson().toJsonTree(u, AbstractCpsObject.class));
  176. // and its connections too
  177. edgeToJson(EDGETYPE.CONNECTION, file, u.getId(), u.getConnections());
  178. // if holonobject elements too
  179. if (u instanceof HolonObject)
  180. elementsToJson(TYPE.CANVAS, file, u);
  181. // if switch graphpoints too
  182. if (u instanceof HolonSwitch)
  183. if (((HolonSwitch) u).getGraphPoints().size() != 0)
  184. unitgraphToJson(GRAPHTYPE.SWITCH, file, u.getId(), ((HolonSwitch) u).getGraphPoints());
  185. // if uppernode put all nodes inside the uppernode into queue
  186. if (u instanceof CpsUpperNode) {
  187. for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
  188. queue.add(adjacent);
  189. }
  190. // dont forget to add the nodeedges and oldedges
  191. edgeToJson(EDGETYPE.NODE, file, u.getId(), ((CpsUpperNode) u).getNodeEdges());
  192. edgeToJson(EDGETYPE.OLD, file, u.getId(), ((CpsUpperNode) u).getOldEdges());
  193. }
  194. }
  195. // lastly add canvasedges into json
  196. edgeToJson(EDGETYPE.CANVAS, file, 0, model.getEdgesOnCanvas());
  197. }
  198. private void storeStatistics(JsonObject file) {
  199. trackedToJson(file);
  200. statisticgraphToJson(file);
  201. }
  202. /**
  203. * Save wanted Data
  204. */
  205. private void storeData(ArchiveOutputStream stream) throws IOException {
  206. File images = new File(System.getProperty("user.home") + "/.config/HolonGUI/Images");
  207. File background = new File(System.getProperty("user.home") + "/.config/HolonGUI/BackgroundImages");
  208. addFilesToSave(images, stream);
  209. addFilesToSave(background, stream);
  210. }
  211. /**
  212. * Stores Category or Canvas Elements into Json
  213. */
  214. void elementsToJson(TYPE type, JsonObject file, AbstractCpsObject obj) {
  215. JsonObject temp = new JsonObject();
  216. String key = null;
  217. // forall elements store them into json and include the id of the object
  218. for (HolonElement ele : ((HolonObject) obj).getElements()) {
  219. temp.add("properties", model.getGson().toJsonTree(ele));
  220. temp.add("ID", new JsonPrimitive(obj.getId()));
  221. // switch for deciding the key
  222. switch (type) {
  223. case CANVAS:
  224. key = "CVSELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  225. break;
  226. case CATEGORY:
  227. key = "CGELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  228. break;
  229. default:
  230. break;
  231. }
  232. file.add(key, model.getGson().toJsonTree(temp));
  233. // if there are gps add them into
  234. if (!ele.getTestGraphPoints().isEmpty())
  235. unitgraphTESTToJson(file, ele.getId(), ele.getTestGraphPoints());
  236. temp = new JsonObject();
  237. }
  238. }
  239. /**
  240. * Put the UnitGraphs of Switches or Elements into Json
  241. */
  242. void unitgraphToJson(GRAPHTYPE type, JsonObject file, int id, LinkedList<Point> graph) {
  243. JsonObject temp = new JsonObject();
  244. String key = null;
  245. // forall points add them
  246. for (int i = 0; i < graph.size(); i++) {
  247. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  248. }
  249. // decide key
  250. switch (type) {
  251. case SWITCH:
  252. key = "SWUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  253. break;
  254. case ELEMENT:
  255. key = "ELEUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  256. break;
  257. case TESTELEMENT:
  258. key = "ELETESTUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  259. break;
  260. default:
  261. break;
  262. }
  263. // add id of element so it can be found again
  264. temp.add("ID", new JsonPrimitive(id));
  265. file.add(key, model.getGson().toJsonTree(temp));
  266. }
  267. /**
  268. * Put the UnitGraphs of Switches or Elements into Json
  269. */
  270. void unitgraphTESTToJson(JsonObject file, int id, LinkedList<Point2D.Double> graph) {
  271. JsonObject temp = new JsonObject();
  272. String key = null;
  273. // forall points add them
  274. for (int i = 0; i < graph.size(); i++) {
  275. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  276. }
  277. key = "ELETESTUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  278. // add id of element so it can be found again
  279. temp.add("ID", new JsonPrimitive(id));
  280. file.add(key, model.getGson().toJsonTree(temp));
  281. }
  282. /**
  283. * Canvas-Edge, Connections, Node-Edge and Old-Edges to json
  284. */
  285. private void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
  286. String k = null;
  287. boolean b = false;
  288. JsonObject temp = new JsonObject();
  289. for (CpsEdge edge : arr) {
  290. // add properties and only the ids from a and b
  291. temp.add("properties", model.getGson().toJsonTree(edge));
  292. temp.add("A", new JsonPrimitive(edge.getA().getId()));
  293. temp.add("B", new JsonPrimitive(edge.getB().getId()));
  294. // Key and occasionally the id of Uppernode
  295. switch (type) {
  296. case CANVAS:
  297. k = "CVSEDGE" + getNumerator(NUMTYPE.EDGE);
  298. break;
  299. case CONNECTION:
  300. k = "CONNEDGE" + getNumerator(NUMTYPE.CONNECTION);
  301. break;
  302. case NODE:
  303. temp.add("ID", new JsonPrimitive(id));
  304. k = "NODEEDGE" + getNumerator(NUMTYPE.NODEEDGE);
  305. break;
  306. case OLD:
  307. temp.add("ID", new JsonPrimitive(id));
  308. k = "OLDEDGE" + getNumerator(NUMTYPE.OLDEDGE);
  309. break;
  310. default:
  311. break;
  312. }
  313. // lookup if the CVS, NODE or OLDEDGE are also connections
  314. if (edge.getA().getConnections().contains(edge) && edge.getA().getConnections().contains(edge)
  315. && !type.equals(EDGETYPE.CONNECTION))
  316. b = true;
  317. temp.add("connection", new JsonPrimitive(b));
  318. file.add(k, model.getGson().toJsonTree(temp));
  319. temp = new JsonObject();
  320. }
  321. }
  322. private void trackedToJson(JsonObject file) {
  323. JsonObject temp = new JsonObject();
  324. String key = "TRACKED";
  325. // forall points add them
  326. for (int i = 0; i < model.getTrackingObj().size(); i++) {
  327. temp.add("" + i, new JsonPrimitive(model.getTrackingObj().get(i).getId()));
  328. }
  329. file.add(key, model.getGson().toJsonTree(temp));
  330. }
  331. private void statisticgraphToJson(JsonObject file) {
  332. JsonObject temp = new JsonObject();
  333. List<String> keys = new ArrayList<>(model.getGraphTable().keySet());
  334. for (String k : keys) {
  335. JsonObject dataSet = new JsonObject();
  336. for (int i = 0; i < model.getGraphTable().get(k).getStatGraph().getDataSets().size(); i++) {
  337. TrackedDataSet set = model.getGraphTable().get(k).getStatGraph().getDataSets().get(i);
  338. AbstractCpsObject cps = set.getCpsObject();
  339. dataSet.add("ID", (cps == null ? null : new JsonPrimitive(cps.getId())));
  340. dataSet.add("COLOR", model.getGson().toJsonTree(set.getColor(), Color.class));
  341. dataSet.add("PROPERTY", new JsonPrimitive(set.getProperty()));
  342. temp.add("" + i, model.getGson().toJsonTree(dataSet));
  343. dataSet = new JsonObject();
  344. }
  345. temp.add("KEY", new JsonPrimitive(k));
  346. file.add("STATSGRAPH" + getNumerator(NUMTYPE.STATSGRAPH), model.getGson().toJsonTree(temp));
  347. temp = new JsonObject();
  348. }
  349. }
  350. /**
  351. * Differs Between Single file or whole Directory to Store
  352. */
  353. private void addFilesToSave(File src, ArchiveOutputStream stream) throws IOException {
  354. if (!src.exists())
  355. return;
  356. ArrayList<File> files = new ArrayList<>();
  357. files.addAll(Arrays.asList(src.listFiles()));
  358. for (File file : files) {
  359. if (file.isDirectory())
  360. addFilesToSave(file, stream);
  361. else
  362. addFileToSave(file, stream, true);
  363. }
  364. }
  365. /**
  366. * Add a File into the Archive
  367. */
  368. private void addFileToSave(File src, ArchiveOutputStream stream, boolean dir) throws IOException {
  369. String entryName = (dir ? src.getCanonicalPath() : src.getName());
  370. entryName = checkOS(entryName);
  371. ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
  372. stream.putArchiveEntry(entry);
  373. BufferedInputStream input = new BufferedInputStream(new FileInputStream(src));
  374. IOUtils.copy(input, stream);
  375. input.close();
  376. stream.closeArchiveEntry();
  377. }
  378. private String checkOS(String entryName) {
  379. String os = System.getProperty("os.name").toLowerCase();
  380. String ret = entryName;
  381. String partition = null;
  382. if (os.contains("windows")) {
  383. partition = ret.substring(0, ret.indexOf(":") + 1);
  384. ret = ret.replace(System.getProperty("user.home") + "\\.config\\HolonGUI\\", "");
  385. ret = ret.replace(partition, "");
  386. }
  387. if (os.contains("mac")) {
  388. // dosmth
  389. ret = ret.replace(System.getProperty("user.home") + "/.config/HolonGUI/", "");
  390. }
  391. if (os.contains("linux")) {
  392. // dosmth
  393. ret = ret.replace(System.getProperty("user.home") + "/.config/HolonGUI/", "");
  394. }
  395. if (os.contains("solaris")) {
  396. // dosmth
  397. }
  398. return ret;
  399. }
  400. /**
  401. * Just initialize the Numerators for the Json Keys. Maybe bad Style..
  402. */
  403. void initNumeration() {
  404. this.nCat = this.nObj = this.nEle = this.nEdge = this.nConn = this.nNodeEdge = this.nOldEdge = this.nStatsGraph = 0;
  405. }
  406. /**
  407. * Get the wanted numerator and increment it
  408. */
  409. int getNumerator(NUMTYPE type) {
  410. switch (type) {
  411. case CATEGORY:
  412. return nCat++;
  413. case OBJECT:
  414. return nObj++;
  415. case ELEMENT:
  416. return nEle++;
  417. case EDGE:
  418. return nEdge++;
  419. case CONNECTION:
  420. return nConn++;
  421. case NODEEDGE:
  422. return nNodeEdge++;
  423. case OLDEDGE:
  424. return nOldEdge++;
  425. case UNITGRAPH:
  426. return nUnitGraph++;
  427. case STATSGRAPH:
  428. return nStatsGraph++;
  429. default:
  430. break;
  431. }
  432. return -1;
  433. }
  434. public enum MODE {
  435. COMPLETE, PARTIAL, CATEGORY, SIZE,
  436. }
  437. public enum TYPE {
  438. CATEGORY, CANVAS
  439. }
  440. public enum EDGETYPE {
  441. CANVAS, CONNECTION, NODE, OLD, LAYER
  442. }
  443. public enum NUMTYPE {
  444. CATEGORY, OBJECT, ELEMENT, EDGE, CONNECTION, NODEEDGE, OLDEDGE, UNITGRAPH, STATSGRAPH
  445. }
  446. public enum GRAPHTYPE {
  447. SWITCH, ELEMENT, TESTELEMENT
  448. }
  449. }