SaveController.java 14 KB

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