StoreController.java 13 KB

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