SaveController.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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 classes.StorageElement;
  7. import org.apache.commons.compress.archivers.ArchiveException;
  8. import org.apache.commons.compress.archivers.ArchiveOutputStream;
  9. import org.apache.commons.compress.archivers.ArchiveStreamFactory;
  10. import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
  11. import org.apache.commons.compress.utils.IOUtils;
  12. import ui.model.Model;
  13. import java.awt.*;
  14. import java.awt.geom.Point2D;
  15. import java.io.*;
  16. import java.util.*;
  17. import java.util.List;
  18. /**
  19. * Controller for Storage.
  20. *
  21. * @author Gruppe14
  22. */
  23. public class SaveController {
  24. private Model model;
  25. private int nCat, nObj, nEle, nEdge, nConn, nNodeEdge, nOldEdge, nUnitGraph, nStatsGraph;
  26. /**
  27. * Constructor.
  28. *
  29. * @param model the Model
  30. */
  31. SaveController(Model model) {
  32. this.model = model;
  33. }
  34. /**
  35. * Writes the current State of the Modelling into a JSON File which can be
  36. * loaded.
  37. *
  38. * @param path the Path
  39. * @throws IOException exception
  40. */
  41. void writeSave(String path) throws IOException, ArchiveException {
  42. File dst = new File(path);
  43. File holonFile = File.createTempFile("tmp", ".json");
  44. holonFile.deleteOnExit();
  45. dst.delete();
  46. OutputStream output = new FileOutputStream(dst);
  47. ArchiveOutputStream stream = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP,
  48. output);
  49. initNumeration();
  50. JsonObject file = new JsonObject();
  51. initialize(MODE.COMPLETE, file);
  52. storeCategory(file);
  53. storeCanvas(file);
  54. storeStatistics(file);
  55. storeData(stream);
  56. FileWriter writer = new FileWriter(holonFile);
  57. writer.write(model.getGson().toJson(file));
  58. writer.flush();
  59. writer.close();
  60. addFileToSave(holonFile, stream, false);
  61. stream.finish();
  62. output.close();
  63. }
  64. /**
  65. * Writes the windows status (its position and dimensions)
  66. *
  67. * @param path the Path where to save it
  68. */
  69. void writeWindowStatus(String path, int x, int y, int width, int height) 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 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. if (ele instanceof StorageElement) {
  220. temp.add("storageProperties", model.getGson().toJsonTree((StorageElement) ele));
  221. }
  222. else {
  223. temp.add("properties", model.getGson().toJsonTree(ele));
  224. }
  225. temp.add("ID", new JsonPrimitive(obj.getId()));
  226. temp.add("FlexList", model.getGson().toJsonTree(ele.flexList, new TypeToken<List<Flexibility>>() {
  227. }.getType()));
  228. // switch for deciding the key
  229. switch (type) {
  230. case CANVAS:
  231. key = "CVSELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  232. break;
  233. case CATEGORY:
  234. key = "CGELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  235. break;
  236. default:
  237. break;
  238. }
  239. file.add(key, model.getGson().toJsonTree(temp));
  240. // if there are gps add them into
  241. if (!ele.getGraphPoints().isEmpty())
  242. unitgraphTESTToJson(file, ele.getId(), ele.getGraphPoints());
  243. temp = new JsonObject();
  244. }
  245. }
  246. /**
  247. * Put the UnitGraphs of Switches or Elements into Json
  248. */
  249. void unitgraphToJson(GRAPHTYPE type, JsonObject file, int id, LinkedList<Point2D.Double> graph) {
  250. JsonObject temp = new JsonObject();
  251. String key = null;
  252. // forall points add them
  253. for (int i = 0; i < graph.size(); i++) {
  254. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  255. }
  256. // decide key
  257. switch (type) {
  258. case SWITCH:
  259. key = "SWUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  260. break;
  261. case ELEMENT:
  262. key = "ELEUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  263. break;
  264. case TESTELEMENT:
  265. key = "ELETESTUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  266. break;
  267. default:
  268. break;
  269. }
  270. // add id of element so it can be found again
  271. temp.add("ID", new JsonPrimitive(id));
  272. file.add(key, model.getGson().toJsonTree(temp));
  273. }
  274. /**
  275. * Put the UnitGraphs of Switches or Elements into Json
  276. */
  277. void unitgraphTESTToJson(JsonObject file, int id, LinkedList<Point2D.Double> graph) {
  278. JsonObject temp = new JsonObject();
  279. String key = null;
  280. // forall points add them
  281. for (int i = 0; i < graph.size(); i++) {
  282. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  283. }
  284. key = "ELETESTUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  285. // add id of element so it can be found again
  286. temp.add("ID", new JsonPrimitive(id));
  287. file.add(key, model.getGson().toJsonTree(temp));
  288. }
  289. /**
  290. * Canvas-Edge, Connections, Node-Edge and Old-Edges to json
  291. */
  292. private void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
  293. String k = null;
  294. boolean b = false;
  295. JsonObject temp = new JsonObject();
  296. for (CpsEdge edge : arr) {
  297. // add properties and only the ids from a and b
  298. temp.add("properties", model.getGson().toJsonTree(edge));
  299. temp.add("A", new JsonPrimitive(edge.getA().getId()));
  300. temp.add("B", new JsonPrimitive(edge.getB().getId()));
  301. // Key and occasionally the id of Uppernode
  302. switch (type) {
  303. case CANVAS:
  304. k = "CVSEDGE" + getNumerator(NUMTYPE.EDGE);
  305. break;
  306. case CONNECTION:
  307. k = "CONNEDGE" + getNumerator(NUMTYPE.CONNECTION);
  308. break;
  309. case NODE:
  310. temp.add("ID", new JsonPrimitive(id));
  311. k = "NODEEDGE" + getNumerator(NUMTYPE.NODEEDGE);
  312. break;
  313. case OLD:
  314. temp.add("ID", new JsonPrimitive(id));
  315. k = "OLDEDGE" + getNumerator(NUMTYPE.OLDEDGE);
  316. break;
  317. default:
  318. break;
  319. }
  320. // lookup if the CVS, NODE or OLDEDGE are also connections
  321. if (edge.getA().getConnections().contains(edge) && edge.getA().getConnections().contains(edge)
  322. && !type.equals(EDGETYPE.CONNECTION))
  323. b = true;
  324. temp.add("connection", new JsonPrimitive(b));
  325. file.add(k, model.getGson().toJsonTree(temp));
  326. temp = new JsonObject();
  327. }
  328. }
  329. private void trackedToJson(JsonObject file) {
  330. JsonObject temp = new JsonObject();
  331. String key = "TRACKED";
  332. // forall points add them
  333. for (int i = 0; i < model.getTrackingObj().size(); i++) {
  334. temp.add("" + i, new JsonPrimitive(model.getTrackingObj().get(i).getId()));
  335. }
  336. file.add(key, model.getGson().toJsonTree(temp));
  337. }
  338. private void statisticgraphToJson(JsonObject file) {
  339. JsonObject temp = new JsonObject();
  340. List<String> keys = new ArrayList<>(model.getGraphTable().keySet());
  341. for (String k : keys) {
  342. JsonObject dataSet = new JsonObject();
  343. for (int i = 0; i < model.getGraphTable().get(k).getStatGraph().getDataSets().size(); i++) {
  344. TrackedDataSet set = model.getGraphTable().get(k).getStatGraph().getDataSets().get(i);
  345. AbstractCpsObject cps = set.getCpsObject();
  346. dataSet.add("ID", (cps == null ? null : new JsonPrimitive(cps.getId())));
  347. dataSet.add("COLOR", model.getGson().toJsonTree(set.getColor(), Color.class));
  348. dataSet.add("PROPERTY", new JsonPrimitive(set.getProperty()));
  349. temp.add("" + i, model.getGson().toJsonTree(dataSet));
  350. dataSet = new JsonObject();
  351. }
  352. temp.add("KEY", new JsonPrimitive(k));
  353. file.add("STATSGRAPH" + getNumerator(NUMTYPE.STATSGRAPH), model.getGson().toJsonTree(temp));
  354. temp = new JsonObject();
  355. }
  356. }
  357. /**
  358. * Differs Between Single file or whole Directory to Store
  359. */
  360. private void addFilesToSave(File src, ArchiveOutputStream stream) throws IOException {
  361. if (!src.exists())
  362. return;
  363. ArrayList<File> files = new ArrayList<>();
  364. files.addAll(Arrays.asList(src.listFiles()));
  365. for (File file : files) {
  366. if (file.isDirectory())
  367. addFilesToSave(file, stream);
  368. else
  369. addFileToSave(file, stream, true);
  370. }
  371. }
  372. /**
  373. * Add a File into the Archive
  374. */
  375. private void addFileToSave(File src, ArchiveOutputStream stream, boolean dir) throws IOException {
  376. String entryName = (dir ? src.getCanonicalPath() : src.getName());
  377. entryName = checkOS(entryName);
  378. ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
  379. stream.putArchiveEntry(entry);
  380. BufferedInputStream input = new BufferedInputStream(new FileInputStream(src));
  381. IOUtils.copy(input, stream);
  382. input.close();
  383. stream.closeArchiveEntry();
  384. }
  385. private String checkOS(String entryName) {
  386. String os = System.getProperty("os.name").toLowerCase();
  387. String ret = entryName;
  388. String partition = null;
  389. if (os.contains("windows")) {
  390. partition = ret.substring(0, ret.indexOf(":") + 1);
  391. ret = ret.replace(System.getProperty("user.home") + "\\.config\\HolonGUI\\", "");
  392. ret = ret.replace(partition, "");
  393. }
  394. if (os.contains("mac")) {
  395. // dosmth
  396. ret = ret.replace(System.getProperty("user.home") + "/.config/HolonGUI/", "");
  397. }
  398. if (os.contains("linux")) {
  399. // dosmth
  400. ret = ret.replace(System.getProperty("user.home") + "/.config/HolonGUI/", "");
  401. }
  402. if (os.contains("solaris")) {
  403. // dosmth
  404. }
  405. return ret;
  406. }
  407. /**
  408. * Just initialize the Numerators for the Json Keys. Maybe bad Style..
  409. */
  410. void initNumeration() {
  411. this.nCat = this.nObj = this.nEle = this.nEdge = this.nConn = this.nNodeEdge = this.nOldEdge = this.nStatsGraph = 0;
  412. }
  413. /**
  414. * Get the wanted numerator and increment it
  415. */
  416. int getNumerator(NUMTYPE type) {
  417. switch (type) {
  418. case CATEGORY:
  419. return nCat++;
  420. case OBJECT:
  421. return nObj++;
  422. case ELEMENT:
  423. return nEle++;
  424. case EDGE:
  425. return nEdge++;
  426. case CONNECTION:
  427. return nConn++;
  428. case NODEEDGE:
  429. return nNodeEdge++;
  430. case OLDEDGE:
  431. return nOldEdge++;
  432. case UNITGRAPH:
  433. return nUnitGraph++;
  434. case STATSGRAPH:
  435. return nStatsGraph++;
  436. default:
  437. break;
  438. }
  439. return -1;
  440. }
  441. public enum MODE {
  442. COMPLETE, PARTIAL, CATEGORY, SIZE,
  443. }
  444. public enum TYPE {
  445. CATEGORY, CANVAS
  446. }
  447. public enum EDGETYPE {
  448. CANVAS, CONNECTION, NODE, OLD, LAYER
  449. }
  450. public enum NUMTYPE {
  451. CATEGORY, OBJECT, ELEMENT, EDGE, CONNECTION, NODEEDGE, OLDEDGE, UNITGRAPH, STATSGRAPH
  452. }
  453. public enum GRAPHTYPE {
  454. SWITCH, ELEMENT, TESTELEMENT
  455. }
  456. }