StoreController.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 StoreController {
  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 StoreController(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. System.out.println(images.getCanonicalPath());
  221. addFilesToSave(images, stream);
  222. addFilesToSave(background, stream);
  223. }
  224. /**
  225. * Stores Category or Canvas Elements into Json
  226. *
  227. * @param type
  228. * @param gson
  229. * @param file
  230. * @param obj
  231. */
  232. public void elementsToJson(TYPE type, JsonObject file, AbstractCpsObject obj) {
  233. // TODO Auto-generated method stub
  234. JsonObject temp = new JsonObject();
  235. String key = null;
  236. // forall elements store them into json and include the id of the object
  237. for (HolonElement ele : ((HolonObject) obj).getElements()) {
  238. temp.add("properties", gson.toJsonTree(ele));
  239. temp.add("ID", new JsonPrimitive(obj.getId()));
  240. // switch for deciding the key
  241. switch (type) {
  242. case CANVAS:
  243. key = "CVSELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  244. break;
  245. case CATEGORY:
  246. key = "CGELEMENT" + getNumerator(NUMTYPE.ELEMENT);
  247. break;
  248. default:
  249. break;
  250. }
  251. file.add(key, gson.toJsonTree(temp));
  252. // if there are gps add them into
  253. if (ele.getGraphPoints().size() != 0)
  254. unitgraphToJson(GRAPHTYPE.ELEMENT, file, ele.getId(), ele.getGraphPoints());
  255. temp = new JsonObject();
  256. }
  257. }
  258. /**
  259. * Put the UnitGraphs of Switches or Elements into Json
  260. *
  261. * @param ele
  262. */
  263. public void unitgraphToJson(GRAPHTYPE type, JsonObject file, int id, LinkedList<Point> graph) {
  264. JsonObject temp = new JsonObject();
  265. String key = null;
  266. // forall points add them
  267. for (int i = 0; i < graph.size(); i++) {
  268. temp.add("" + i, new JsonPrimitive(graph.get(i).x + ":" + graph.get(i).y));
  269. }
  270. // decide key
  271. switch (type) {
  272. case SWITCH:
  273. key = "SWUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  274. break;
  275. case ELEMENT:
  276. key = "ELEUNITGRAPH" + getNumerator(NUMTYPE.UNITGRAPH);
  277. break;
  278. default:
  279. break;
  280. }
  281. // add id of element so it can be found again
  282. temp.add("ID", new JsonPrimitive(id));
  283. file.add(key, gson.toJsonTree(temp));
  284. }
  285. /**
  286. * Canvas-Edge, Connections, Node-Edge and Old-Edges to json
  287. *
  288. * @param type
  289. * @param file
  290. * @param id
  291. * @param arr
  292. */
  293. public void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
  294. // TODO Auto-generated method stub
  295. String k = null;
  296. boolean b = false;
  297. JsonObject temp = new JsonObject();
  298. for (CpsEdge edge : arr) {
  299. // add properties and only the ids from a and b
  300. temp.add("properties", gson.toJsonTree(edge));
  301. temp.add("A", new JsonPrimitive(edge.getA().getId()));
  302. temp.add("B", new JsonPrimitive(edge.getB().getId()));
  303. // Key and occasionally the id of Uppernode
  304. switch (type) {
  305. case CANVAS:
  306. k = "CVSEDGE" + getNumerator(NUMTYPE.EDGE);
  307. break;
  308. case CONNECTION:
  309. k = "CONNEDGE" + getNumerator(NUMTYPE.CONNECTION);
  310. break;
  311. case NODE:
  312. temp.add("ID", new JsonPrimitive(id));
  313. k = "NODEEDGE" + getNumerator(NUMTYPE.NODEEDGE);
  314. break;
  315. case OLD:
  316. temp.add("ID", new JsonPrimitive(id));
  317. k = "OLDEDGE" + getNumerator(NUMTYPE.OLDEDGE);
  318. break;
  319. default:
  320. break;
  321. }
  322. // lookup if the CVS, NODE or OLDEDGE are also connections
  323. if (edge.getA().getConnections().contains(edge) && edge.getA().getConnections().contains(edge)
  324. && !type.equals(EDGETYPE.CONNECTION))
  325. b = true;
  326. temp.add("connection", new JsonPrimitive(b));
  327. file.add(k, gson.toJsonTree(temp));
  328. temp = new JsonObject();
  329. }
  330. }
  331. /**
  332. * Differs Between Single file or whole Directory to Store
  333. *
  334. * @param src
  335. * @param stream
  336. * @throws IOException
  337. */
  338. private void addFilesToSave(File src, ArchiveOutputStream stream) throws IOException {
  339. if (!src.exists())
  340. return;
  341. ArrayList<File> files = new ArrayList<>();
  342. files.addAll(Arrays.asList(src.listFiles()));
  343. for (File file : files) {
  344. if (file.isDirectory())
  345. addFilesToSave(file, stream);
  346. else
  347. addFileToSave(file, stream, true);
  348. }
  349. }
  350. /**
  351. * Add a File into the Archive
  352. *
  353. * @param src
  354. * @param stream
  355. * @param dir
  356. * @throws IOException
  357. */
  358. private void addFileToSave(File src, ArchiveOutputStream stream, boolean dir) throws IOException {
  359. String entryName = (dir == true ? src.getCanonicalPath() : src.getName());
  360. entryName = entryName.replace(System.getProperty("user.home") + "/HolonGUI/", "");
  361. ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
  362. stream.putArchiveEntry(entry);
  363. BufferedInputStream input = new BufferedInputStream(new FileInputStream(src));
  364. IOUtils.copy(input, stream);
  365. input.close();
  366. stream.closeArchiveEntry();
  367. }
  368. /**
  369. * Initialize the Gson with wanted parameters
  370. */
  371. private void initGson() {
  372. // TODO Auto-generated method stub
  373. GsonBuilder builder = new GsonBuilder();
  374. builder.excludeFieldsWithoutExposeAnnotation().serializeNulls().setPrettyPrinting();
  375. builder.registerTypeAdapter(AbstractCpsObject.class, new AbstractCpsObjectAdapter());
  376. builder.registerTypeAdapter(Position.class, new PositionAdapter());
  377. builder.registerTypeAdapter(Color.class, new ColorAdapter());
  378. // use the builder and make a instance of the Gson
  379. this.gson = builder.create();
  380. }
  381. /**
  382. * Just initialize the Numerators for the Json Keys. Maybe bad Style..
  383. */
  384. public void initNumeration() {
  385. this.nCat = this.nObj = this.nEle = this.nEdge = this.nConn = this.nNodeEdge = this.nOldEdge = this.nImg = 0;
  386. }
  387. /**
  388. * Get the wanted numerator and increment it
  389. *
  390. * @param type
  391. * @return
  392. */
  393. public int getNumerator(NUMTYPE type) {
  394. switch (type) {
  395. case CATEGORY:
  396. return nCat++;
  397. case OBJECT:
  398. return nObj++;
  399. case ELEMENT:
  400. return nEle++;
  401. case EDGE:
  402. return nEdge++;
  403. case CONNECTION:
  404. return nConn++;
  405. case NODEEDGE:
  406. return nNodeEdge++;
  407. case OLDEDGE:
  408. return nOldEdge++;
  409. case UNITGRAPH:
  410. return nUnitGraph++;
  411. case IMAGE:
  412. return nImg++;
  413. default:
  414. break;
  415. }
  416. return -1;
  417. }
  418. }