LoadController.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. package ui.controller;
  2. import classes.*;
  3. import com.google.gson.JsonElement;
  4. import com.google.gson.JsonObject;
  5. import com.google.gson.JsonParser;
  6. import com.google.gson.reflect.TypeToken;
  7. import org.apache.commons.compress.archivers.ArchiveEntry;
  8. import org.apache.commons.compress.archivers.ArchiveException;
  9. import org.apache.commons.compress.archivers.ArchiveInputStream;
  10. import org.apache.commons.compress.archivers.ArchiveStreamFactory;
  11. import org.apache.commons.compress.utils.IOUtils;
  12. import ui.model.Model;
  13. import java.awt.geom.Point2D;
  14. import java.io.*;
  15. import java.nio.file.Files;
  16. import java.nio.file.StandardCopyOption;
  17. import java.util.ArrayList;
  18. import java.util.HashMap;
  19. import java.util.LinkedList;
  20. import java.util.List;
  21. import java.util.stream.Collectors;
  22. /**
  23. * Controller for the Loading.
  24. *
  25. * @author Gruppe14
  26. */
  27. public class LoadController {
  28. private Model model;
  29. private CategoryController cgC;
  30. private CanvasController cvsC;
  31. private ObjectController objC;
  32. private NodeController uppC;
  33. private MultiPurposeController mpC;
  34. private JsonParser parser;
  35. /**
  36. * Constructor.
  37. *
  38. * @param model Model
  39. * @param cg CategoryController
  40. * @param cvs CanvasController
  41. * @param obj ObjectController
  42. * @param mp MultiPurposeController
  43. */
  44. LoadController(Model model, CategoryController cg, CanvasController cvs, ObjectController obj,
  45. NodeController uppC, MultiPurposeController mp) {
  46. this.model = model;
  47. this.cgC = cg;
  48. this.cvsC = cvs;
  49. this.objC = obj;
  50. this.uppC = uppC;
  51. this.mpC = mp;
  52. this.parser = new JsonParser();
  53. }
  54. /**
  55. * Reads the the JSON File and load the state into the Model.
  56. *
  57. * @param path the Path
  58. * @throws IOException exception
  59. */
  60. void readSave(String path) throws IOException, ArchiveException {
  61. File src = new File(path);
  62. File folder = readArchive(src);
  63. folder.deleteOnExit();
  64. String trim = folder.getPath().substring(0,
  65. folder.getPath().lastIndexOf(folder.getName()) + folder.getName().length());
  66. forwardFiles(folder, trim);
  67. }
  68. /**
  69. * reads the dimensions file containing the saved position and dimensions of the frame
  70. *
  71. * @return a list of the form [x, y, width, height]
  72. */
  73. ArrayList<Integer> readWindowDimensions(String path) throws FileNotFoundException {
  74. JsonObject json = (JsonObject) parser.parse(new FileReader(path));
  75. ArrayList<Integer> dimensions = new ArrayList<>();
  76. List<String> keys = getKeys(json);
  77. for (int i = 1; i < 5; i++) {
  78. dimensions.add(json.get(keys.get(i)).getAsInt());
  79. }
  80. return dimensions;
  81. }
  82. void readJson(String path) throws IOException {
  83. JsonObject json = (JsonObject) parser.parse(new FileReader(path));
  84. // get all keys via stream
  85. List<String> keys = getKeys(json);
  86. List<String> edges = keys.stream().filter(key -> key.contains("EDGE"))
  87. .collect(Collectors.toCollection(ArrayList::new));
  88. HashMap<Integer, AbstractCanvasObject> objDispatch = new HashMap<>();
  89. HashMap<Integer, HolonElement> eleDispatch = new HashMap<>();
  90. initialize(json);
  91. forwardObjects(keys, json, objDispatch, eleDispatch);
  92. forwardEdges(edges, json, objDispatch);
  93. }
  94. /**
  95. * Loads the Files from the Savefile
  96. *
  97. * @param trim the part of the file's path to be trimmed
  98. * @throws IOException if anythings goes wrong reading the files
  99. */
  100. private void forwardFiles(File folder, String trim) throws IOException {
  101. for (File file : folder.listFiles()) {
  102. File dst = new File(
  103. System.getProperty("user.home") + "/.config/HolonGUI/" + file.getPath().replace(trim, ""));
  104. if (file.getName().contains(".json"))
  105. readJson(file.getPath());
  106. else if (file.isDirectory())
  107. forwardFiles(file, trim);
  108. else {
  109. dst.getParentFile().mkdirs();
  110. Files.copy(file.toPath(), dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
  111. }
  112. }
  113. }
  114. /**
  115. * distribute the Edges
  116. */
  117. private void forwardEdges(List<String> edges, JsonObject json, HashMap<Integer, AbstractCanvasObject> objDispatch) {
  118. for (String edge : edges) {
  119. if (edge.contains("CVSEDGE"))
  120. loadEdge(EDGETYPE.CANVAS, json.get(edge), objDispatch);
  121. if (edge.contains("CONNEDGE"))
  122. loadEdge(EDGETYPE.CONNECTION, json.get(edge), objDispatch);
  123. if (edge.contains("NODE"))
  124. loadEdge(EDGETYPE.NODE, json.get(edge), objDispatch);
  125. if (edge.contains("OLD"))
  126. loadEdge(EDGETYPE.OLD, json.get(edge), objDispatch);
  127. }
  128. }
  129. /**
  130. * Distribute the given keys for right processing
  131. */
  132. private void forwardObjects(List<String> keys, JsonObject json, HashMap<Integer, AbstractCanvasObject> objDispatch,
  133. HashMap<Integer, HolonElement> eleDispatch) {
  134. for (String key : keys) {
  135. if (key.contains("CATEGORY"))
  136. loadCategory(json.get(key));
  137. if (key.contains("CGOBJECT"))
  138. loadCategoryObject(json.get(key));
  139. if (key.contains("CGELEMENT"))
  140. loadCategoryElements(json.get(key), eleDispatch);//TODO
  141. if (key.contains("CVSOBJECT"))
  142. loadCanvasObject(json.get(key), objDispatch);
  143. if (key.contains("CVSELEMENT"))
  144. loadCanvasElements(json.get(key), objDispatch, eleDispatch);
  145. if (key.contains("SWUNITGRAPH"))
  146. loadUnitGraph(GRAPHTYPE.SWITCH, json.get(key), objDispatch, null);
  147. if (key.contains("ELEUNITGRAPH"))
  148. loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
  149. if (key.contains("ELETESTUNITGRAPH"))
  150. loadUnitGraph(GRAPHTYPE.TESTELEMENT, json.get(key), null, eleDispatch);
  151. if (key.contains("TRACKED"))
  152. loadTracked(json.get(key), objDispatch);
  153. }
  154. }
  155. /**
  156. * Init the Global Parameters
  157. */
  158. private void initialize(JsonObject json) {
  159. switch (MODE.valueOf(json.get("MODE").getAsString())) {
  160. case COMPLETE:
  161. model.setCvsObjIdx(new HashMap<>());
  162. model.setObjectsOnCanvas(new ArrayList<>());
  163. model.setEdgesOnCanvas(new ArrayList<>());
  164. model.setHashcodeMap(new HashMap<>());
  165. model.setCanvasX(json.get("CANVAS_SIZE_X").getAsInt());
  166. model.setCanvasX(json.get("CANVAS_SIZE_Y").getAsInt());
  167. IdCounter.setCounter(json.get("IDCOUNTER").getAsInt());
  168. IdCounterElem.setCounter(json.get("IDCOUNTERELEMENT").getAsInt());
  169. break;
  170. case PARTIAL:
  171. model.setCvsObjIdx(new HashMap<>());
  172. model.setObjectsOnCanvas(new ArrayList<>());
  173. model.setEdgesOnCanvas(new ArrayList<>());
  174. model.setHashcodeMap(new HashMap<>());
  175. model.setCanvasX(json.get("CANVAS_SIZE_X").getAsInt());
  176. model.setCanvasX(json.get("CANVAS_SIZE_Y").getAsInt());
  177. IdCounter.setCounter(json.get("IDCOUNTER").getAsInt());
  178. IdCounterElem.setCounter(json.get("IDCOUNTERELEMENT").getAsInt());
  179. break;
  180. case CATEGORY:
  181. model.setCgIdx(new HashMap<>());
  182. model.setCategories(new ArrayList<>());
  183. default:
  184. break;
  185. }
  186. }
  187. /**
  188. * Load a given Category
  189. */
  190. private void loadCategory(JsonElement jsonElement) {
  191. if (mpC.searchCat(jsonElement.getAsString()) == null)
  192. cgC.addCategory(new Category(jsonElement.getAsString()));
  193. }
  194. /**
  195. * Load a given Object in Category by Deserialization
  196. */
  197. private void loadCategoryObject(JsonElement jsonElement) {
  198. AbstractCanvasObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCanvasObject.class);
  199. temp.setImage(checkOS(temp.getImage()));
  200. initObjects(temp);
  201. if (mpC.searchCatObj(mpC.searchCat(temp.getSav()), temp.getObjName()) != null)
  202. cgC.deleteObject(temp.getSav(), temp.getObjName());
  203. cgC.addObject(mpC.searchCat(temp.getSav()), temp);
  204. }
  205. /**
  206. * Load a given Element in Category by Deserialization
  207. * @param eleDispatch
  208. */
  209. private void loadCategoryElements(JsonElement jsonElement, HashMap<Integer, HolonElement> eleDispatch) {
  210. HolonElement temp = model.getGson().fromJson(jsonElement.getAsJsonObject().get("properties").getAsJsonObject(),
  211. HolonElement.class);
  212. eleDispatch.put(temp.getId(), temp);
  213. initElements(temp);
  214. objC.addElementIntoCategoryObject(temp.getSaving().getKey(), temp.getSaving().getValue(), temp);
  215. }
  216. /**
  217. * Load a given Object in Canvas by Deserialization
  218. */
  219. private void loadCanvasObject(JsonElement jsonElement, HashMap<Integer, AbstractCanvasObject> objDispatch) {
  220. AbstractCanvasObject temp = null;
  221. if(jsonElement.getAsJsonObject().get("type").getAsString().equals("CpsUpperNode")) {
  222. //Change Old Name
  223. jsonElement.getAsJsonObject().addProperty("type", "GroupNode");
  224. }
  225. try{
  226. temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCanvasObject.class);
  227. }catch(java.lang.ClassCastException e) {
  228. System.err.println("ClassRenameError");
  229. e.printStackTrace();
  230. return;
  231. }
  232. initObjects(temp);
  233. temp.setImage(checkOS(temp.getImage()));
  234. if (temp instanceof GroupNode) {
  235. model.getHashcodeMap().put(jsonElement.getAsJsonObject().get("hash").getAsInt(), (GroupNode) temp);
  236. ((GroupNode) temp).setLeftBorder(jsonElement.getAsJsonObject().get("properties").getAsJsonObject().get("leftBorder").getAsInt());
  237. }
  238. // if its stored before on the canvas just put it there
  239. if (temp.getSav().equals("CVS")) {
  240. cvsC.addObject(temp, false);
  241. } else {
  242. // else look up the table and put it into the right Uppernode
  243. GroupNode temp2 = (GroupNode) objDispatch.get(Integer.parseInt(temp.getSav()));
  244. if(temp2 != null)
  245. uppC.addObjectInUpperNode(temp, temp2, false);
  246. else{
  247. /**
  248. * if null try to load on canvas
  249. */
  250. cvsC.addObject(temp, false);
  251. }
  252. }
  253. objDispatch.put(temp.getId(), temp);
  254. }
  255. /**
  256. * Load a given Element in Canvas by Deserialization
  257. */
  258. private void loadCanvasElements(JsonElement jsonElement, HashMap<Integer, AbstractCanvasObject> objDispatch,
  259. HashMap<Integer, HolonElement> eleDispatch) {
  260. JsonObject object = jsonElement.getAsJsonObject();
  261. HolonElement ele = model.getGson().fromJson(object.get("properties"), HolonElement.class);
  262. initElements(ele);
  263. ele.flexList = model.getGson().fromJson(object.get("FlexList"), new TypeToken<List<Flexibility>>() {}.getType());
  264. //object.get("FlexList").getAsJsonArray().forEach(jo -> System.out.println("Hallo"));
  265. //object.get("FlexList").getAsJsonArray().forEach(flexJson -> flexJson.getAsJsonObject().get("constrainList").getAsJsonArray().forEach(constrainJson -> System.out.println("Constrain:" + constrainJson.getAsJsonObject().get("name").getAsString())));
  266. ele.flexList.stream().forEach(flex -> {
  267. flex.setElement(ele);
  268. flex.constrainList.forEach(con -> con.fixJson());
  269. });
  270. // id which Object it was stored before
  271. int stored = object.get("ID").getAsInt();
  272. // lookup that object
  273. HolonObject hObject = (HolonObject) objDispatch.get(stored);
  274. // add it
  275. objC.addElement(hObject, ele);
  276. ele.parentObject = hObject;
  277. // store element also inside a table
  278. eleDispatch.put(ele.getId(), ele);
  279. }
  280. /**
  281. * Load a given Edge by Deserialization
  282. */
  283. private void loadEdge(EDGETYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCanvasObject> objDispatch) {
  284. JsonObject object = jsonElement.getAsJsonObject();
  285. Edge temp = model.getGson().fromJson(object.get("properties"), Edge.class);
  286. initCpsEdge(temp);
  287. // look for A and B inside the Table
  288. temp.setA(objDispatch.get(object.get("A").getAsInt()));
  289. temp.setB(objDispatch.get(object.get("B").getAsInt()));
  290. model.getEdgesOnCanvas().add(temp);
  291. }
  292. /**
  293. * Load a Unitgraph by Deserialization
  294. */
  295. private void loadUnitGraph(GRAPHTYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCanvasObject> objDispatch,
  296. HashMap<Integer, HolonElement> eleDispatch) {
  297. //TODO Make UnitGraph unterscheidung hinf�llig!!!!
  298. JsonObject object = jsonElement.getAsJsonObject();
  299. List<String> keys = getKeys(object);
  300. String p;
  301. int mid;
  302. int sav = 0;
  303. LinkedList<Point2D.Double> graphpointTEST = new LinkedList<>();
  304. for (String k : keys) {
  305. if (!k.equals("ID")) {
  306. p = object.get(k).getAsString();
  307. mid = p.indexOf(':');
  308. double x1 = Double.parseDouble(p.substring(0, mid));
  309. double y1 = Double.parseDouble(p.substring(mid + 1, p.length()));
  310. graphpointTEST.add(new Point2D.Double(x1, y1));
  311. } else
  312. // else its an ID
  313. sav = object.get(k).getAsInt();
  314. }
  315. switch (type) {
  316. case SWITCH:
  317. HolonSwitch sw = (HolonSwitch) objDispatch.get(sav);
  318. sw.setGraphPoints(graphpointTEST);
  319. sw.sampleGraph();
  320. break;
  321. case ELEMENT:
  322. System.out.println("Write me new");
  323. break;
  324. case TESTELEMENT:
  325. HolonElement ele1 = eleDispatch.get(sav);
  326. ele1.setGraphPoints(graphpointTEST);
  327. ele1.sampleGraph();
  328. break;
  329. default:
  330. break;
  331. }
  332. }
  333. private void loadTracked(JsonElement jsonElement, HashMap<Integer, AbstractCanvasObject> objDispatch) {
  334. JsonObject object = jsonElement.getAsJsonObject();
  335. List<String> keys = getKeys(object);
  336. for (String k : keys) {
  337. int id = object.get(k).getAsInt();
  338. if (objDispatch.get(id) instanceof HolonObject) {
  339. ((HolonObject) objDispatch.get(id)).updateTrackingInfo();
  340. }
  341. }
  342. }
  343. private File readArchive(File src) throws IOException, ArchiveException {
  344. File tmp = Files.createTempDirectory("tmpHolon").toFile();
  345. tmp.deleteOnExit();
  346. InputStream input = new FileInputStream(src);
  347. ArchiveInputStream stream = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP,
  348. input);
  349. ArchiveEntry entry = stream.getNextEntry();
  350. while (entry != null) {
  351. // String entryName = checkOS(entry.getName());
  352. File file = new File(tmp, entry.getName());
  353. file.getParentFile().mkdirs();
  354. OutputStream output = new FileOutputStream(file);
  355. IOUtils.copy(stream, output);
  356. output.close();
  357. // file.createNewFile();
  358. entry = stream.getNextEntry();
  359. }
  360. stream.close();
  361. input.close();
  362. return tmp;
  363. }
  364. private String checkOS(String entryName) {
  365. String os = System.getProperty("os.name").toLowerCase();
  366. String ret = entryName;
  367. // String partition = System.getProperty("user.home");
  368. if (!ret.contains("HolonGUI"))
  369. return ret;
  370. if (os.contains("windows")) {
  371. ret = ret.replace("/", "\\");
  372. ret = System.getProperty("user.home") + "\\.config"
  373. + ret.substring(ret.indexOf("\\HolonGUI\\"), ret.length());
  374. }
  375. if (os.contains("mac")) {
  376. // dosmth
  377. ret = ret.replace("\\", "/");
  378. ret = System.getProperty("user.home") + "/.config" + ret.substring(ret.indexOf("/HolonGUI/"), ret.length());
  379. }
  380. if (os.contains("linux")) {
  381. // dosmth
  382. ret = ret.replace("\\", "/");
  383. ret = System.getProperty("user.home") + "/.config" + ret.substring(ret.indexOf("/HolonGUI/"), ret.length());
  384. }
  385. // if (os.contains("solaris")) {
  386. // // dosmth
  387. // }
  388. return ret;
  389. }
  390. /**
  391. * Init new Arrays which haven't been serialized along the object
  392. */
  393. void initObjects(AbstractCanvasObject obj) {
  394. obj.setConnections(new ArrayList<>());
  395. if (obj instanceof HolonObject) {
  396. ((HolonObject) obj).setElements(new ArrayList<>());
  397. }
  398. if (obj instanceof HolonSwitch) {
  399. ((HolonSwitch) obj).setGraphPoints(new LinkedList<>());
  400. ((HolonSwitch) obj).reset();
  401. ((HolonSwitch) obj).sampleGraph();
  402. }
  403. if (obj instanceof GroupNode) {
  404. ((GroupNode) obj).setNodes(new ArrayList<>());
  405. ((GroupNode) obj).setNodesIdx(new HashMap<>());
  406. }
  407. }
  408. /**
  409. * Init Elements (set available energy, set new graph points)
  410. *
  411. * @param ele the element to be initialized
  412. */
  413. void initElements(HolonElement ele) {
  414. ele.flexList = new ArrayList<Flexibility>();
  415. ele.setGraphPoints(new LinkedList<>());
  416. ele.reset();
  417. }
  418. /**
  419. * Init Edges (set tags and reset source and target)
  420. *
  421. * @param edge the edge to be initialized
  422. */
  423. void initCpsEdge(Edge edge) {
  424. edge.setTags(new ArrayList<>());
  425. edge.setA(null);
  426. edge.setB(null);
  427. }
  428. /**
  429. * Get Set of Keys
  430. *
  431. * @return the keys from the json object
  432. */
  433. List<String> getKeys(JsonObject json) {
  434. return json.entrySet().stream().map(i -> i.getKey()).collect(Collectors.toCollection(ArrayList::new));
  435. }
  436. /**
  437. * enum Mode. (in SaveController there is an additional mode called SIZE,
  438. * it is not currently needed here and was therefore not added)
  439. */
  440. public enum MODE {
  441. COMPLETE, PARTIAL, CATEGORY
  442. }
  443. public enum EDGETYPE {
  444. CANVAS, CONNECTION, NODE, OLD
  445. }
  446. public enum GRAPHTYPE {
  447. SWITCH, ELEMENT, TESTELEMENT
  448. }
  449. }