SaveController.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. package ui.controller;
  2. import classes.*;
  3. import classes.IdCounter.CounterType;
  4. import com.google.gson.JsonObject;
  5. import com.google.gson.JsonPrimitive;
  6. import com.google.gson.reflect.TypeToken;
  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.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. storeData(stream);
  54. FileWriter writer = new FileWriter(holonFile);
  55. writer.write(model.getGson().toJson(file));
  56. writer.flush();
  57. writer.close();
  58. addFileToSave(holonFile, stream, false);
  59. stream.finish();
  60. output.close();
  61. }
  62. /**
  63. * Writes the windows status (its position and dimensions)
  64. *
  65. * @param path the Path where to save it
  66. */
  67. void writeWindowStatus(String path, int x, int y, int width, int height)
  68. throws IOException, ArchiveException {
  69. JsonObject file = new JsonObject();
  70. initialize(MODE.SIZE, file);
  71. storeWindowPosAndSize(file, x, y, width, height);
  72. FileWriter writer = new FileWriter(path);
  73. writer.write(model.getGson().toJson(file));
  74. writer.flush();
  75. writer.close();
  76. }
  77. /**
  78. * Writes the Autosave File.
  79. *
  80. * @param path the Path
  81. * @throws IOException Exception
  82. */
  83. void writeAutosave(String path) throws IOException {
  84. initNumeration();
  85. JsonObject file = new JsonObject();
  86. initialize(MODE.PARTIAL, file);
  87. storeCanvas(file);
  88. FileWriter writer = new FileWriter(path);
  89. writer.write(model.getGson().toJson(file));
  90. writer.flush();
  91. writer.close();
  92. }
  93. /**
  94. * Writes the Category File in Case of Changes
  95. */
  96. void writeCategory(String path) throws IOException {
  97. initNumeration();
  98. JsonObject file = new JsonObject();
  99. initialize(MODE.CATEGORY, file);
  100. storeCategory(file);
  101. FileWriter writer = new FileWriter(path);
  102. writer.write(model.getGson().toJson(file));
  103. writer.flush();
  104. writer.close();
  105. }
  106. /**
  107. * Write needed default parameter into the JsonObject. Can be extended later
  108. * 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.actualId(CounterType.Object)));
  115. file.add("IDCOUNTERELEMENT", new JsonPrimitive(IdCounter.actualId(CounterType.Element)));
  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.actualId(CounterType.Object)));
  122. file.add("IDCOUNTERELEMENT", new JsonPrimitive(IdCounter.actualId(CounterType.Element)));
  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 (AbstractCanvasObject obj : cat.getObjects()) {
  145. file.add("CGOBJECT" + getNumerator(NUMTYPE.OBJECT),
  146. model.getGson().toJsonTree(obj, AbstractCanvasObject.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<AbstractCanvasObject> queue = new ArrayDeque<>();
  164. AbstractCanvasObject u = null;
  165. // put all objects into queue since there is not starting object
  166. for (AbstractCanvasObject 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, AbstractCanvasObject.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 GroupNode) {
  187. for (AbstractCanvasObject adjacent : ((GroupNode) u).getNodes()) {
  188. queue.add(adjacent);
  189. }
  190. }
  191. }
  192. // lastly add canvasedges into json
  193. edgeToJson(EDGETYPE.CANVAS, file, 0, model.getEdgesOnCanvas());
  194. }
  195. /**
  196. * Save wanted Data
  197. */
  198. private void storeData(ArchiveOutputStream stream) throws IOException {
  199. File images = new File(System.getProperty("user.home") + "/.config/HolonGUI/Images");
  200. File background = new File(System.getProperty("user.home") + "/.config/HolonGUI/BackgroundImages");
  201. addFilesToSave(images, stream);
  202. addFilesToSave(background, stream);
  203. }
  204. /**
  205. * Stores Category or Canvas Elements into Json
  206. */
  207. void elementsToJson(TYPE type, JsonObject file, AbstractCanvasObject obj) {
  208. JsonObject temp = new JsonObject();
  209. String key = null;
  210. // forall elements store them into json and include the id of the object
  211. for (HolonElement ele : ((HolonObject) obj).getElements()) {
  212. temp.add("properties", model.getGson().toJsonTree(ele));
  213. temp.add("ID", new JsonPrimitive(obj.getId()));
  214. temp.add("FlexList", model.getGson().toJsonTree(ele.flexList, new TypeToken<List<Flexibility>>() {
  215. }.getType()));
  216. // switch for deciding the key
  217. switch (type) {
  218. case CANVAS:
  219. key = "CVSELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  220. break;
  221. case CATEGORY:
  222. key = "CGELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  223. break;
  224. default:
  225. break;
  226. }
  227. file.add(key, model.getGson().toJsonTree(temp));
  228. // if there are gps add them into
  229. if (!ele.getGraphPoints().isEmpty())
  230. unitgraphTESTToJson(file, ele.getId(), ele.getGraphPoints());
  231. temp = new JsonObject();
  232. }
  233. }
  234. /**
  235. * Put the UnitGraphs of Switches or Elements into Json
  236. */
  237. void unitgraphToJson(GRAPHTYPE type, JsonObject file, int id, LinkedList<Point2D.Double> graph) {
  238. JsonObject temp = new JsonObject();
  239. String key = null;
  240. // forall points add them
  241. for (int i = 0; i < graph.size(); i++) {
  242. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  243. }
  244. // decide key
  245. switch (type) {
  246. case SWITCH:
  247. key = "SWUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  248. break;
  249. case ELEMENT:
  250. key = "ELEUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  251. break;
  252. case TESTELEMENT:
  253. key = "ELETESTUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  254. break;
  255. default:
  256. break;
  257. }
  258. // add id of element so it can be found again
  259. temp.add("ID", new JsonPrimitive(id));
  260. file.add(key, model.getGson().toJsonTree(temp));
  261. }
  262. /**
  263. * Put the UnitGraphs of Switches or Elements into Json
  264. */
  265. void unitgraphTESTToJson(JsonObject file, int id, LinkedList<Point2D.Double> graph) {
  266. JsonObject temp = new JsonObject();
  267. String key = null;
  268. // forall points add them
  269. for (int i = 0; i < graph.size(); i++) {
  270. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  271. }
  272. key = "ELETESTUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  273. // add id of element so it can be found again
  274. temp.add("ID", new JsonPrimitive(id));
  275. file.add(key, model.getGson().toJsonTree(temp));
  276. }
  277. /**
  278. * Canvas-Edge, Connections, Node-Edge and Old-Edges to json
  279. */
  280. private void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<Edge> arr) {
  281. String k = null;
  282. boolean b = false;
  283. JsonObject temp = new JsonObject();
  284. for (Edge edge : arr) {
  285. // add properties and only the ids from a and b
  286. temp.add("properties", model.getGson().toJsonTree(edge));
  287. temp.add("A", new JsonPrimitive(edge.getA().getId()));
  288. temp.add("B", new JsonPrimitive(edge.getB().getId()));
  289. // Key and occasionally the id of Uppernode
  290. switch (type) {
  291. case CANVAS:
  292. k = "CVSEDGE" + getNumerator(NUMTYPE.EDGE);
  293. break;
  294. case CONNECTION:
  295. k = "CONNEDGE" + getNumerator(NUMTYPE.CONNECTION);
  296. break;
  297. case NODE:
  298. temp.add("ID", new JsonPrimitive(id));
  299. k = "NODEEDGE" + getNumerator(NUMTYPE.NODEEDGE);
  300. break;
  301. case OLD:
  302. temp.add("ID", new JsonPrimitive(id));
  303. k = "OLDEDGE" + getNumerator(NUMTYPE.OLDEDGE);
  304. break;
  305. default:
  306. break;
  307. }
  308. // lookup if the CVS, NODE or OLDEDGE are also connections
  309. if (edge.getA().getConnections().contains(edge) && edge.getA().getConnections().contains(edge)
  310. && !type.equals(EDGETYPE.CONNECTION))
  311. b = true;
  312. temp.add("connection", new JsonPrimitive(b));
  313. file.add(k, model.getGson().toJsonTree(temp));
  314. temp = new JsonObject();
  315. }
  316. }
  317. /**
  318. * Differs Between Single file or whole Directory to Store
  319. */
  320. private void addFilesToSave(File src, ArchiveOutputStream stream) throws IOException {
  321. if (!src.exists())
  322. return;
  323. ArrayList<File> files = new ArrayList<>();
  324. files.addAll(Arrays.asList(src.listFiles()));
  325. for (File file : files) {
  326. if (file.isDirectory())
  327. addFilesToSave(file, stream);
  328. else
  329. addFileToSave(file, stream, true);
  330. }
  331. }
  332. /**
  333. * Add a File into the Archive
  334. */
  335. private void addFileToSave(File src, ArchiveOutputStream stream, boolean dir) throws IOException {
  336. String entryName = (dir ? src.getCanonicalPath() : src.getName());
  337. entryName = checkOS(entryName);
  338. ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
  339. stream.putArchiveEntry(entry);
  340. BufferedInputStream input = new BufferedInputStream(new FileInputStream(src));
  341. IOUtils.copy(input, stream);
  342. input.close();
  343. stream.closeArchiveEntry();
  344. }
  345. private String checkOS(String entryName) {
  346. String os = System.getProperty("os.name").toLowerCase();
  347. String ret = entryName;
  348. String partition = null;
  349. if (os.contains("windows")) {
  350. partition = ret.substring(0, ret.indexOf(":") + 1);
  351. ret = ret.replace(System.getProperty("user.home") + "\\.config\\HolonGUI\\", "");
  352. ret = ret.replace(partition, "");
  353. }
  354. if (os.contains("mac")) {
  355. // dosmth
  356. ret = ret.replace(System.getProperty("user.home") + "/.config/HolonGUI/", "");
  357. }
  358. if (os.contains("linux")) {
  359. // dosmth
  360. ret = ret.replace(System.getProperty("user.home") + "/.config/HolonGUI/", "");
  361. }
  362. if (os.contains("solaris")) {
  363. // dosmth
  364. }
  365. return ret;
  366. }
  367. /**
  368. * Just initialize the Numerators for the Json Keys. Maybe bad Style..
  369. */
  370. void initNumeration() {
  371. this.nCat = this.nObj = this.nEle = this.nEdge = this.nConn = this.nNodeEdge = this.nOldEdge = this.nStatsGraph = 0;
  372. }
  373. /**
  374. * Get the wanted numerator and increment it
  375. */
  376. int getNumerator(NUMTYPE type) {
  377. switch (type) {
  378. case CATEGORY:
  379. return nCat++;
  380. case OBJECT:
  381. return nObj++;
  382. case ELEMENT:
  383. return nEle++;
  384. case EDGE:
  385. return nEdge++;
  386. case CONNECTION:
  387. return nConn++;
  388. case NODEEDGE:
  389. return nNodeEdge++;
  390. case OLDEDGE:
  391. return nOldEdge++;
  392. case UNITGRAPH:
  393. return nUnitGraph++;
  394. case STATSGRAPH:
  395. return nStatsGraph++;
  396. default:
  397. break;
  398. }
  399. return -1;
  400. }
  401. public enum MODE {
  402. COMPLETE, PARTIAL, CATEGORY, SIZE,
  403. }
  404. public enum TYPE {
  405. CATEGORY, CANVAS
  406. }
  407. public enum EDGETYPE {
  408. CANVAS, CONNECTION, NODE, OLD, LAYER
  409. }
  410. public enum NUMTYPE {
  411. CATEGORY, OBJECT, ELEMENT, EDGE, CONNECTION, NODEEDGE, OLDEDGE, UNITGRAPH, STATSGRAPH
  412. }
  413. public enum GRAPHTYPE {
  414. SWITCH, ELEMENT, TESTELEMENT
  415. }
  416. }