SaveController.java 17 KB

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