SaveController.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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 (AbstractCpsObject obj : cat.getObjects()) {
  146. file.add("CGOBJECT" + getNumerator(NUMTYPE.OBJECT),
  147. model.getGson().toJsonTree(obj, AbstractCpsObject.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<AbstractCpsObject> queue = new ArrayDeque<>();
  165. AbstractCpsObject u = null;
  166. // put all objects into queue since there is not starting object
  167. for (AbstractCpsObject 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, AbstractCpsObject.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 CpsUpperNode) {
  188. for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
  189. queue.add(adjacent);
  190. }
  191. // dont forget to add the nodeedges and oldedges
  192. edgeToJson(EDGETYPE.NODE, file, u.getId(), ((CpsUpperNode) u).getNodeEdges());
  193. edgeToJson(EDGETYPE.OLD, file, u.getId(), ((CpsUpperNode) u).getOldEdges());
  194. }
  195. }
  196. // lastly add canvasedges into json
  197. edgeToJson(EDGETYPE.CANVAS, file, 0, model.getEdgesOnCanvas());
  198. }
  199. private void storeStatistics(JsonObject file) {
  200. trackedToJson(file);
  201. statisticgraphToJson(file);
  202. }
  203. /**
  204. * Save wanted Data
  205. */
  206. private void storeData(ArchiveOutputStream stream) throws IOException {
  207. File images = new File(System.getProperty("user.home") + "/.config/HolonGUI/Images");
  208. File background = new File(System.getProperty("user.home") + "/.config/HolonGUI/BackgroundImages");
  209. addFilesToSave(images, stream);
  210. addFilesToSave(background, stream);
  211. }
  212. /**
  213. * Stores Category or Canvas Elements into Json
  214. */
  215. void elementsToJson(TYPE type, JsonObject file, AbstractCpsObject obj) {
  216. JsonObject temp = new JsonObject();
  217. String key = null;
  218. // forall elements store them into json and include the id of the object
  219. for (HolonElement ele : ((HolonObject) obj).getElements()) {
  220. temp.add("properties", model.getGson().toJsonTree(ele));
  221. temp.add("ID", new JsonPrimitive(obj.getId()));
  222. temp.add("FlexList", model.getGson().toJsonTree(ele.flexList, new TypeToken<List<Flexibility>>() {
  223. }.getType()));
  224. // switch for deciding the key
  225. switch (type) {
  226. case CANVAS:
  227. key = "CVSELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  228. break;
  229. case CATEGORY:
  230. key = "CGELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  231. break;
  232. default:
  233. break;
  234. }
  235. file.add(key, model.getGson().toJsonTree(temp));
  236. // if there are gps add them into
  237. if (!ele.getGraphPoints().isEmpty())
  238. unitgraphTESTToJson(file, ele.getId(), ele.getGraphPoints());
  239. temp = new JsonObject();
  240. }
  241. }
  242. /**
  243. * Put the UnitGraphs of Switches or Elements into Json
  244. */
  245. void unitgraphToJson(GRAPHTYPE type, JsonObject file, int id, LinkedList<Point2D.Double> graph) {
  246. JsonObject temp = new JsonObject();
  247. String key = null;
  248. // forall points add them
  249. for (int i = 0; i < graph.size(); i++) {
  250. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  251. }
  252. // decide key
  253. switch (type) {
  254. case SWITCH:
  255. key = "SWUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  256. break;
  257. case ELEMENT:
  258. key = "ELEUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  259. break;
  260. case TESTELEMENT:
  261. key = "ELETESTUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  262. break;
  263. default:
  264. break;
  265. }
  266. // add id of element so it can be found again
  267. temp.add("ID", new JsonPrimitive(id));
  268. file.add(key, model.getGson().toJsonTree(temp));
  269. }
  270. /**
  271. * Put the UnitGraphs of Switches or Elements into Json
  272. */
  273. void unitgraphTESTToJson(JsonObject file, int id, LinkedList<Point2D.Double> graph) {
  274. JsonObject temp = new JsonObject();
  275. String key = null;
  276. // forall points add them
  277. for (int i = 0; i < graph.size(); i++) {
  278. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  279. }
  280. key = "ELETESTUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  281. // add id of element so it can be found again
  282. temp.add("ID", new JsonPrimitive(id));
  283. file.add(key, model.getGson().toJsonTree(temp));
  284. }
  285. /**
  286. * Canvas-Edge, Connections, Node-Edge and Old-Edges to json
  287. */
  288. private void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
  289. String k = null;
  290. boolean b = false;
  291. JsonObject temp = new JsonObject();
  292. for (CpsEdge edge : arr) {
  293. // add properties and only the ids from a and b
  294. temp.add("properties", model.getGson().toJsonTree(edge));
  295. temp.add("A", new JsonPrimitive(edge.getA().getId()));
  296. temp.add("B", new JsonPrimitive(edge.getB().getId()));
  297. // Key and occasionally the id of Uppernode
  298. switch (type) {
  299. case CANVAS:
  300. k = "CVSEDGE" + getNumerator(NUMTYPE.EDGE);
  301. break;
  302. case CONNECTION:
  303. k = "CONNEDGE" + getNumerator(NUMTYPE.CONNECTION);
  304. break;
  305. case NODE:
  306. temp.add("ID", new JsonPrimitive(id));
  307. k = "NODEEDGE" + getNumerator(NUMTYPE.NODEEDGE);
  308. break;
  309. case OLD:
  310. temp.add("ID", new JsonPrimitive(id));
  311. k = "OLDEDGE" + getNumerator(NUMTYPE.OLDEDGE);
  312. break;
  313. default:
  314. break;
  315. }
  316. // lookup if the CVS, NODE or OLDEDGE are also connections
  317. if (edge.getA().getConnections().contains(edge) && edge.getA().getConnections().contains(edge)
  318. && !type.equals(EDGETYPE.CONNECTION))
  319. b = true;
  320. temp.add("connection", new JsonPrimitive(b));
  321. file.add(k, model.getGson().toJsonTree(temp));
  322. temp = new JsonObject();
  323. }
  324. }
  325. private void trackedToJson(JsonObject file) {
  326. JsonObject temp = new JsonObject();
  327. String key = "TRACKED";
  328. // forall points add them
  329. for (int i = 0; i < model.getTrackingObj().size(); i++) {
  330. temp.add("" + i, new JsonPrimitive(model.getTrackingObj().get(i).getId()));
  331. }
  332. file.add(key, model.getGson().toJsonTree(temp));
  333. }
  334. private void statisticgraphToJson(JsonObject file) {
  335. JsonObject temp = new JsonObject();
  336. List<String> keys = new ArrayList<>(model.getGraphTable().keySet());
  337. for (String k : keys) {
  338. JsonObject dataSet = new JsonObject();
  339. for (int i = 0; i < model.getGraphTable().get(k).getStatGraph().getDataSets().size(); i++) {
  340. TrackedDataSet set = model.getGraphTable().get(k).getStatGraph().getDataSets().get(i);
  341. AbstractCpsObject cps = set.getCpsObject();
  342. dataSet.add("ID", (cps == null ? null : new JsonPrimitive(cps.getId())));
  343. dataSet.add("COLOR", model.getGson().toJsonTree(set.getColor(), Color.class));
  344. dataSet.add("PROPERTY", new JsonPrimitive(set.getProperty()));
  345. temp.add("" + i, model.getGson().toJsonTree(dataSet));
  346. dataSet = new JsonObject();
  347. }
  348. temp.add("KEY", new JsonPrimitive(k));
  349. file.add("STATSGRAPH" + getNumerator(NUMTYPE.STATSGRAPH), model.getGson().toJsonTree(temp));
  350. temp = new JsonObject();
  351. }
  352. }
  353. /**
  354. * Differs Between Single file or whole Directory to Store
  355. */
  356. private void addFilesToSave(File src, ArchiveOutputStream stream) throws IOException {
  357. if (!src.exists())
  358. return;
  359. ArrayList<File> files = new ArrayList<>();
  360. files.addAll(Arrays.asList(src.listFiles()));
  361. for (File file : files) {
  362. if (file.isDirectory())
  363. addFilesToSave(file, stream);
  364. else
  365. addFileToSave(file, stream, true);
  366. }
  367. }
  368. /**
  369. * Add a File into the Archive
  370. */
  371. private void addFileToSave(File src, ArchiveOutputStream stream, boolean dir) throws IOException {
  372. String entryName = (dir ? src.getCanonicalPath() : src.getName());
  373. entryName = checkOS(entryName);
  374. ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
  375. stream.putArchiveEntry(entry);
  376. BufferedInputStream input = new BufferedInputStream(new FileInputStream(src));
  377. IOUtils.copy(input, stream);
  378. input.close();
  379. stream.closeArchiveEntry();
  380. }
  381. private String checkOS(String entryName) {
  382. String os = System.getProperty("os.name").toLowerCase();
  383. String ret = entryName;
  384. String partition = null;
  385. if (os.contains("windows")) {
  386. partition = ret.substring(0, ret.indexOf(":") + 1);
  387. ret = ret.replace(System.getProperty("user.home") + "\\.config\\HolonGUI\\", "");
  388. ret = ret.replace(partition, "");
  389. }
  390. if (os.contains("mac")) {
  391. // dosmth
  392. ret = ret.replace(System.getProperty("user.home") + "/.config/HolonGUI/", "");
  393. }
  394. if (os.contains("linux")) {
  395. // dosmth
  396. ret = ret.replace(System.getProperty("user.home") + "/.config/HolonGUI/", "");
  397. }
  398. if (os.contains("solaris")) {
  399. // dosmth
  400. }
  401. return ret;
  402. }
  403. /**
  404. * Just initialize the Numerators for the Json Keys. Maybe bad Style..
  405. */
  406. void initNumeration() {
  407. this.nCat = this.nObj = this.nEle = this.nEdge = this.nConn = this.nNodeEdge = this.nOldEdge = this.nStatsGraph = 0;
  408. }
  409. /**
  410. * Get the wanted numerator and increment it
  411. */
  412. int getNumerator(NUMTYPE type) {
  413. switch (type) {
  414. case CATEGORY:
  415. return nCat++;
  416. case OBJECT:
  417. return nObj++;
  418. case ELEMENT:
  419. return nEle++;
  420. case EDGE:
  421. return nEdge++;
  422. case CONNECTION:
  423. return nConn++;
  424. case NODEEDGE:
  425. return nNodeEdge++;
  426. case OLDEDGE:
  427. return nOldEdge++;
  428. case UNITGRAPH:
  429. return nUnitGraph++;
  430. case STATSGRAPH:
  431. return nStatsGraph++;
  432. default:
  433. break;
  434. }
  435. return -1;
  436. }
  437. public enum MODE {
  438. COMPLETE, PARTIAL, CATEGORY, SIZE,
  439. }
  440. public enum TYPE {
  441. CATEGORY, CANVAS
  442. }
  443. public enum EDGETYPE {
  444. CANVAS, CONNECTION, NODE, OLD, LAYER
  445. }
  446. public enum NUMTYPE {
  447. CATEGORY, OBJECT, ELEMENT, EDGE, CONNECTION, NODEEDGE, OLDEDGE, UNITGRAPH, STATSGRAPH
  448. }
  449. public enum GRAPHTYPE {
  450. SWITCH, ELEMENT, TESTELEMENT
  451. }
  452. }