SaveController.java 13 KB

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