SaveController.java 13 KB

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