StoreController.java 13 KB

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