SaveController.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. package ui.controller;
  2. import classes.*;
  3. import com.google.gson.JsonObject;
  4. import com.google.gson.JsonPrimitive;
  5. import com.google.gson.reflect.TypeToken;
  6. import org.apache.commons.compress.archivers.ArchiveException;
  7. import org.apache.commons.compress.archivers.ArchiveOutputStream;
  8. import org.apache.commons.compress.archivers.ArchiveStreamFactory;
  9. import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
  10. import org.apache.commons.compress.utils.IOUtils;
  11. import ui.model.Model;
  12. import java.awt.*;
  13. import java.awt.geom.Point2D;
  14. import java.io.*;
  15. import java.util.*;
  16. import java.util.List;
  17. /**
  18. * Controller for Storage.
  19. *
  20. * @author Gruppe14
  21. */
  22. public class SaveController {
  23. private Model model;
  24. private int nCat, nObj, nEle, nEdge, nConn, nNodeEdge, nOldEdge, nUnitGraph, nStatsGraph;
  25. /**
  26. * Constructor.
  27. *
  28. * @param model the Model
  29. */
  30. SaveController(Model model) {
  31. this.model = model;
  32. }
  33. /**
  34. * Writes the current State of the Modelling into a JSON File which can be
  35. * loaded.
  36. *
  37. * @param path the Path
  38. * @throws IOException exception
  39. */
  40. void writeSave(String path) throws IOException, ArchiveException {
  41. File dst = new File(path);
  42. File holonFile = File.createTempFile("tmp", ".json");
  43. holonFile.deleteOnExit();
  44. dst.delete();
  45. OutputStream output = new FileOutputStream(dst);
  46. ArchiveOutputStream stream = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP,
  47. output);
  48. initNumeration();
  49. JsonObject file = new JsonObject();
  50. initialize(MODE.COMPLETE, file);
  51. storeCategory(file);
  52. storeCanvas(file);
  53. storeStatistics(file);
  54. storeData(stream);
  55. FileWriter writer = new FileWriter(holonFile);
  56. writer.write(model.getGson().toJson(file));
  57. writer.flush();
  58. writer.close();
  59. addFileToSave(holonFile, stream, false);
  60. stream.finish();
  61. output.close();
  62. }
  63. /**
  64. * Writes the windows status (its position and dimensions)
  65. *
  66. * @param path the Path where to save it
  67. */
  68. void writeWindowStatus(String path, int x, int y, int width, int height)
  69. throws IOException, ArchiveException {
  70. JsonObject file = new JsonObject();
  71. initialize(MODE.SIZE, file);
  72. storeWindowPosAndSize(file, x, y, width, height);
  73. FileWriter writer = new FileWriter(path);
  74. writer.write(model.getGson().toJson(file));
  75. writer.flush();
  76. writer.close();
  77. }
  78. /**
  79. * Writes the Autosave File.
  80. *
  81. * @param path the Path
  82. * @throws IOException Exception
  83. */
  84. void writeAutosave(String path) throws IOException {
  85. initNumeration();
  86. JsonObject file = new JsonObject();
  87. initialize(MODE.PARTIAL, file);
  88. storeCanvas(file);
  89. FileWriter writer = new FileWriter(path);
  90. writer.write(model.getGson().toJson(file));
  91. writer.flush();
  92. writer.close();
  93. }
  94. /**
  95. * Writes the Category File in Case of Changes
  96. */
  97. void writeCategory(String path) throws IOException {
  98. initNumeration();
  99. JsonObject file = new JsonObject();
  100. initialize(MODE.CATEGORY, file);
  101. storeCategory(file);
  102. FileWriter writer = new FileWriter(path);
  103. writer.write(model.getGson().toJson(file));
  104. writer.flush();
  105. writer.close();
  106. }
  107. /**
  108. * Write needed default parameter into the JsonObject. Can be extended later
  109. * on
  110. */
  111. private void initialize(MODE mode, JsonObject file) {
  112. switch (mode) {
  113. case COMPLETE:
  114. file.add("MODE", new JsonPrimitive(mode.name()));
  115. file.add("IDCOUNTER", new JsonPrimitive(IdCounter.getCounter()));
  116. file.add("IDCOUNTERELEMENT", new JsonPrimitive(IdCounterElem.getCounter()));
  117. file.add("CANVAS_SIZE_X", new JsonPrimitive(model.getCanvasX()));
  118. file.add("CANVAS_SIZE_Y", new JsonPrimitive(model.getCanvasY()));
  119. break;
  120. case PARTIAL:
  121. file.add("MODE", new JsonPrimitive(mode.name()));
  122. file.add("IDCOUNTER", new JsonPrimitive(IdCounter.getCounter()));
  123. file.add("IDCOUNTERELEMENT", new JsonPrimitive(IdCounterElem.getCounter()));
  124. file.add("CANVAS_SIZE_X", new JsonPrimitive(model.getCanvasX()));
  125. file.add("CANVAS_SIZE_Y", new JsonPrimitive(model.getCanvasY()));
  126. break;
  127. case CATEGORY:
  128. file.add("MODE", new JsonPrimitive(mode.name()));
  129. break;
  130. case SIZE:
  131. file.add("MODE", new JsonPrimitive(mode.name()));
  132. default:
  133. break;
  134. }
  135. }
  136. /**
  137. * Store all Categories and Object into a Json File via Serialization
  138. */
  139. private void storeCategory(JsonObject file) {
  140. // forall categories store them into the jsontree
  141. for (Category cat : model.getCategories()) {
  142. String key = "CATEGORY" + getNumerator(NUMTYPE.CATEGORY);
  143. file.add(key, new JsonPrimitive(cat.getName()));
  144. // forall object in the category store them into the jsontree
  145. for (AbstractCanvasObject obj : cat.getObjects()) {
  146. file.add("CGOBJECT" + getNumerator(NUMTYPE.OBJECT),
  147. model.getGson().toJsonTree(obj, AbstractCanvasObject.class));
  148. // if its a holonobject add elements too
  149. if (obj instanceof HolonObject)
  150. elementsToJson(TYPE.CATEGORY, file, obj);
  151. }
  152. }
  153. }
  154. private void storeWindowPosAndSize(JsonObject file, int x, int y, int width, int height) {
  155. file.add("POS_X", new JsonPrimitive(x));
  156. file.add("POS_Y", new JsonPrimitive(y));
  157. file.add("WIDTH", new JsonPrimitive(width));
  158. file.add("HEIGHT", new JsonPrimitive(height));
  159. }
  160. /**
  161. * Travers through all Objects via BFS and Stores everything relevant
  162. */
  163. private void storeCanvas(JsonObject file) {
  164. ArrayDeque<AbstractCanvasObject> queue = new ArrayDeque<>();
  165. AbstractCanvasObject u = null;
  166. // put all objects into queue since there is not starting object
  167. for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
  168. queue.add(cps);
  169. }
  170. // while quene not empty
  171. while (!queue.isEmpty()) {
  172. // u = current node
  173. u = queue.pop();
  174. // add currentnode into jsontree
  175. String key = "CVSOBJECT" + getNumerator(NUMTYPE.OBJECT);
  176. file.add(key, model.getGson().toJsonTree(u, AbstractCanvasObject.class));
  177. // and its connections too
  178. edgeToJson(EDGETYPE.CONNECTION, file, u.getId(), u.getConnections());
  179. // if holonobject elements too
  180. if (u instanceof HolonObject)
  181. elementsToJson(TYPE.CANVAS, file, u);
  182. // if switch graphpoints too
  183. if (u instanceof HolonSwitch)
  184. if (((HolonSwitch) u).getGraphPoints().size() != 0)
  185. unitgraphToJson(GRAPHTYPE.SWITCH, file, u.getId(), ((HolonSwitch) u).getGraphPoints());
  186. // if uppernode put all nodes inside the uppernode into queue
  187. if (u instanceof GroupNode) {
  188. for (AbstractCanvasObject adjacent : ((GroupNode) u).getNodes()) {
  189. queue.add(adjacent);
  190. }
  191. }
  192. }
  193. // lastly add canvasedges into json
  194. edgeToJson(EDGETYPE.CANVAS, file, 0, model.getEdgesOnCanvas());
  195. }
  196. private void storeStatistics(JsonObject file) {
  197. trackedToJson(file);
  198. statisticgraphToJson(file);
  199. }
  200. /**
  201. * Save wanted Data
  202. */
  203. private void storeData(ArchiveOutputStream stream) throws IOException {
  204. File images = new File(System.getProperty("user.home") + "/.config/HolonGUI/Images");
  205. File background = new File(System.getProperty("user.home") + "/.config/HolonGUI/BackgroundImages");
  206. addFilesToSave(images, stream);
  207. addFilesToSave(background, stream);
  208. }
  209. /**
  210. * Stores Category or Canvas Elements into Json
  211. */
  212. void elementsToJson(TYPE type, JsonObject file, AbstractCanvasObject obj) {
  213. JsonObject temp = new JsonObject();
  214. String key = null;
  215. // forall elements store them into json and include the id of the object
  216. for (HolonElement ele : ((HolonObject) obj).getElements()) {
  217. temp.add("properties", model.getGson().toJsonTree(ele));
  218. temp.add("ID", new JsonPrimitive(obj.getId()));
  219. temp.add("FlexList", model.getGson().toJsonTree(ele.flexList, new TypeToken<List<Flexibility>>() {
  220. }.getType()));
  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.getGraphPoints().isEmpty())
  235. unitgraphTESTToJson(file, ele.getId(), ele.getGraphPoints());
  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<Point2D.Double> 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<Edge> arr) {
  286. String k = null;
  287. boolean b = false;
  288. JsonObject temp = new JsonObject();
  289. for (Edge 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. AbstractCanvasObject 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. }