SaveController.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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
  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. * Write needed default parameter into the JsonObject. Can be extended later
  124. * on
  125. *
  126. * @param mode
  127. * @param file
  128. */
  129. private void initialize(MODE mode, JsonObject file) {
  130. // TODO Auto-generated method stub
  131. switch (mode) {
  132. case COMPLETE:
  133. file.add("MODE", new JsonPrimitive(mode.name()));
  134. file.add("IDCOUNTER", new JsonPrimitive(IdCounter.getCounter()));
  135. file.add("IDCOUNTERELEMENT", new JsonPrimitive(IdCounterElem.getCounter()));
  136. file.add("CANVAS_SIZE_X", new JsonPrimitive(model.getCanvasX()));
  137. file.add("CANVAS_SIZE_Y", new JsonPrimitive(model.getCanvasY()));
  138. break;
  139. case PARTIAL:
  140. file.add("MODE", new JsonPrimitive(mode.name()));
  141. file.add("IDCOUNTER", new JsonPrimitive(IdCounter.getCounter()));
  142. file.add("IDCOUNTERELEMENT", new JsonPrimitive(IdCounterElem.getCounter()));
  143. break;
  144. default:
  145. break;
  146. }
  147. }
  148. /**
  149. * Store all Categories and Object into a Json File via Serialization
  150. *
  151. * @param file
  152. */
  153. private void storeCategory(JsonObject file) {
  154. // TODO Auto-generated method stub
  155. // forall categories store them into the jsontree
  156. for (Category cat : model.getCategories()) {
  157. String key = "CATEGORY" + getNumerator(NUMTYPE.CATEGORY);
  158. file.add(key, new JsonPrimitive(cat.getName()));
  159. // forall object in the category store them into the jsontree
  160. for (AbstractCpsObject obj : cat.getObjects()) {
  161. file.add("CGOBJECT" + getNumerator(NUMTYPE.OBJECT), gson.toJsonTree(obj, AbstractCpsObject.class));
  162. // if its a holonobject add elements too
  163. if (obj instanceof HolonObject)
  164. elementsToJson(TYPE.CATEGORY, file, obj);
  165. }
  166. }
  167. }
  168. /**
  169. * Travers through all Objects via BFS and Stores everything relevant
  170. *
  171. * @param file
  172. */
  173. private void storeCanvas(JsonObject file) {
  174. // TODO Auto-generated method stub
  175. ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
  176. AbstractCpsObject u = null;
  177. // put all objects into queue since there is not starting object
  178. for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
  179. queue.add(cps);
  180. }
  181. // while quene not empty
  182. while (!queue.isEmpty()) {
  183. // u = current node
  184. u = queue.pop();
  185. // add currentnode into jsontree
  186. String key = "CVSOBJECT" + getNumerator(NUMTYPE.OBJECT);
  187. file.add(key, gson.toJsonTree(u, AbstractCpsObject.class));
  188. // and its connections too
  189. edgeToJson(EDGETYPE.CONNECTION, file, u.getId(), u.getConnections());
  190. // if holonobject elements too
  191. if (u instanceof HolonObject)
  192. elementsToJson(TYPE.CANVAS, file, u);
  193. // if switch graphpoints too
  194. if (u instanceof HolonSwitch)
  195. if (((HolonSwitch) u).getGraphPoints().size() != 0)
  196. unitgraphToJson(GRAPHTYPE.SWITCH, file, u.getId(), ((HolonSwitch) u).getGraphPoints());
  197. // if uppernode put all nodes inside the uppernode into queue
  198. if (u instanceof CpsUpperNode) {
  199. for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
  200. queue.add(adjacent);
  201. }
  202. // dont forget to add the nodeedges and oldedges
  203. edgeToJson(EDGETYPE.NODE, file, u.getId(), ((CpsUpperNode) u).getNodeEdges());
  204. edgeToJson(EDGETYPE.OLD, file, u.getId(), ((CpsUpperNode) u).getOldEdges());
  205. }
  206. }
  207. // lastly add canvasedges into json
  208. edgeToJson(EDGETYPE.CANVAS, file, 0, model.getEdgesOnCanvas());
  209. }
  210. /**
  211. * Save wanted Data
  212. *
  213. * @param stream
  214. * @throws IOException
  215. */
  216. private void storeData(ArchiveOutputStream stream) throws IOException {
  217. // TODO Auto-generated method stub
  218. File images = new File(System.getProperty("user.home") + "/HolonGUI/Images");
  219. File background = new File(System.getProperty("user.home") + "/HolonGUI/BackgroundImages");
  220. addFilesToSave(images, stream);
  221. addFilesToSave(background, stream);
  222. }
  223. /**
  224. * Stores Category or Canvas Elements into Json
  225. *
  226. * @param type
  227. * @param gson
  228. * @param file
  229. * @param obj
  230. */
  231. public void elementsToJson(TYPE type, JsonObject file, AbstractCpsObject obj) {
  232. // TODO Auto-generated method stub
  233. JsonObject temp = new JsonObject();
  234. String key = null;
  235. // forall elements store them into json and include the id of the object
  236. for (HolonElement ele : ((HolonObject) obj).getElements()) {
  237. temp.add("properties", gson.toJsonTree(ele));
  238. temp.add("ID", new JsonPrimitive(obj.getId()));
  239. // switch for deciding the key
  240. switch (type) {
  241. case CANVAS:
  242. key = "CVSELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  243. break;
  244. case CATEGORY:
  245. key = "CGELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  246. break;
  247. default:
  248. break;
  249. }
  250. file.add(key, gson.toJsonTree(temp));
  251. // if there are gps add them into
  252. if (ele.getGraphPoints().size() != 0)
  253. unitgraphToJson(GRAPHTYPE.ELEMENT, file, ele.getId(), ele.getGraphPoints());
  254. temp = new JsonObject();
  255. }
  256. }
  257. /**
  258. * Put the UnitGraphs of Switches or Elements into Json
  259. *
  260. * @param ele
  261. */
  262. public void unitgraphToJson(GRAPHTYPE type, JsonObject file, int id, LinkedList<Point> graph) {
  263. JsonObject temp = new JsonObject();
  264. String key = null;
  265. // forall points add them
  266. for (int i = 0; i < graph.size(); i++) {
  267. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  268. }
  269. // decide key
  270. switch (type) {
  271. case SWITCH:
  272. key = "SWUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  273. break;
  274. case ELEMENT:
  275. key = "ELEUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  276. break;
  277. default:
  278. break;
  279. }
  280. // add id of element so it can be found again
  281. temp.add("ID", new JsonPrimitive(id));
  282. file.add(key, gson.toJsonTree(temp));
  283. }
  284. /**
  285. * Canvas-Edge, Connections, Node-Edge and Old-Edges to json
  286. *
  287. * @param type
  288. * @param file
  289. * @param id
  290. * @param arr
  291. */
  292. public void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
  293. // TODO Auto-generated method stub
  294. String k = null;
  295. boolean b = false;
  296. JsonObject temp = new JsonObject();
  297. for (CpsEdge edge : arr) {
  298. // add properties and only the ids from a and b
  299. temp.add("properties", gson.toJsonTree(edge));
  300. temp.add("A", new JsonPrimitive(edge.getA().getId()));
  301. temp.add("B", new JsonPrimitive(edge.getB().getId()));
  302. // Key and occasionally the id of Uppernode
  303. switch (type) {
  304. case CANVAS:
  305. k = "CVSEDGE" + getNumerator(NUMTYPE.EDGE);
  306. break;
  307. case CONNECTION:
  308. k = "CONNEDGE" + getNumerator(NUMTYPE.CONNECTION);
  309. break;
  310. case NODE:
  311. temp.add("ID", new JsonPrimitive(id));
  312. k = "NODEEDGE" + getNumerator(NUMTYPE.NODEEDGE);
  313. break;
  314. case OLD:
  315. temp.add("ID", new JsonPrimitive(id));
  316. k = "OLDEDGE" + getNumerator(NUMTYPE.OLDEDGE);
  317. break;
  318. default:
  319. break;
  320. }
  321. // lookup if the CVS, NODE or OLDEDGE are also connections
  322. if (edge.getA().getConnections().contains(edge) && edge.getA().getConnections().contains(edge)
  323. && !type.equals(EDGETYPE.CONNECTION))
  324. b = true;
  325. temp.add("connection", new JsonPrimitive(b));
  326. file.add(k, gson.toJsonTree(temp));
  327. temp = new JsonObject();
  328. }
  329. }
  330. /**
  331. * Differs Between Single file or whole Directory to Store
  332. *
  333. * @param src
  334. * @param stream
  335. * @throws IOException
  336. */
  337. private void addFilesToSave(File src, ArchiveOutputStream stream) throws IOException {
  338. if (!src.exists())
  339. return;
  340. ArrayList<File> files = new ArrayList<>();
  341. files.addAll(Arrays.asList(src.listFiles()));
  342. for (File file : files) {
  343. if (file.isDirectory())
  344. addFilesToSave(file, stream);
  345. else
  346. addFileToSave(file, stream, true);
  347. }
  348. }
  349. /**
  350. * Add a File into the Archive
  351. *
  352. * @param src
  353. * @param stream
  354. * @param dir
  355. * @throws IOException
  356. */
  357. private void addFileToSave(File src, ArchiveOutputStream stream, boolean dir) throws IOException {
  358. String entryName = (dir == true ? src.getCanonicalPath() : src.getName());
  359. entryName = entryName.replace(System.getProperty("user.home") + "/HolonGUI/", "");
  360. ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
  361. stream.putArchiveEntry(entry);
  362. BufferedInputStream input = new BufferedInputStream(new FileInputStream(src));
  363. IOUtils.copy(input, stream);
  364. input.close();
  365. stream.closeArchiveEntry();
  366. }
  367. /**
  368. * Initialize the Gson with wanted parameters
  369. */
  370. private void initGson() {
  371. // TODO Auto-generated method stub
  372. GsonBuilder builder = new GsonBuilder();
  373. builder.excludeFieldsWithoutExposeAnnotation().serializeNulls().setPrettyPrinting();
  374. builder.registerTypeAdapter(AbstractCpsObject.class, new AbstractCpsObjectAdapter());
  375. builder.registerTypeAdapter(Position.class, new PositionAdapter());
  376. builder.registerTypeAdapter(Color.class, new ColorAdapter());
  377. // use the builder and make a instance of the Gson
  378. this.gson = builder.create();
  379. }
  380. /**
  381. * Just initialize the Numerators for the Json Keys. Maybe bad Style..
  382. */
  383. public void initNumeration() {
  384. this.nCat = this.nObj = this.nEle = this.nEdge = this.nConn = this.nNodeEdge = this.nOldEdge = this.nImg = 0;
  385. }
  386. /**
  387. * Get the wanted numerator and increment it
  388. *
  389. * @param type
  390. * @return
  391. */
  392. public int getNumerator(NUMTYPE type) {
  393. switch (type) {
  394. case CATEGORY:
  395. return nCat++;
  396. case OBJECT:
  397. return nObj++;
  398. case ELEMENT:
  399. return nEle++;
  400. case EDGE:
  401. return nEdge++;
  402. case CONNECTION:
  403. return nConn++;
  404. case NODEEDGE:
  405. return nNodeEdge++;
  406. case OLDEDGE:
  407. return nOldEdge++;
  408. case UNITGRAPH:
  409. return nUnitGraph++;
  410. case IMAGE:
  411. return nImg++;
  412. default:
  413. break;
  414. }
  415. return -1;
  416. }
  417. }