From 8013b4289b3ca3fcfa1361e34a0c903b8d6c7682 Mon Sep 17 00:00:00 2001
From: Helena Jank <jank@uni-potsdam.de>
Date: Thu, 7 Jan 2016 19:20:35 +0100
Subject: [PATCH] + added utils containing uuid generator # moved a box
 generation into scenario model, since each scenario is to have its own a box
 + added JSON-LD formatting to scenario and unit model TODO: relations are
 missing! --> must match with t box # ContextInformation: getJSONLD() now
 returns object instead of array # (temporarily) changed showSaveScenario() so
 that a box is downloaded instead of scenario JSON

---
 index.html                                    |  1 +
 .../controllers/saveScenarioController.js     | 15 +++--
 js/authoring/models/aBoxJSONLDModel.js        | 13 ++++-
 js/authoring/models/contextInfoModel.js       | 28 +++++-----
 js/authoring/models/scenarioModel.js          | 26 ++++++++-
 js/authoring/models/unitModel.js              | 55 +++++++++++++++----
 js/authoring/utils.js                         | 19 +++++++
 js/main.js                                    |  1 -
 8 files changed, 124 insertions(+), 34 deletions(-)
 create mode 100644 js/authoring/utils.js

diff --git a/index.html b/index.html
index fdfdb08..39391e0 100644
--- a/index.html
+++ b/index.html
@@ -28,6 +28,7 @@
 
         <script type="text/javascript" src="js/authoring/formatSelections.js"></script>
         <script type="text/javascript" src="js/authoring/dictionaries.js"></script>
+        <script type="text/javascript" src="js/authoring/utils.js"></script>
 
         <!-- models -->
         <script type="text/javascript" src="js/authoring/models/xmlParser.js"></script>
diff --git a/js/authoring/controllers/saveScenarioController.js b/js/authoring/controllers/saveScenarioController.js
index bfe9702..87a37f2 100644
--- a/js/authoring/controllers/saveScenarioController.js
+++ b/js/authoring/controllers/saveScenarioController.js
@@ -11,18 +11,22 @@ $(function() {
  * Function saves current open scenario as a JSON file.
  */
 function showSaveScenario() {
-    var saveScenarioElement = $("#saveScenario");
 
     // get current scenario name
     var currentScenario = $("#lname")[0].innerHTML;
-    var json;
+    if (currentScenario == "") {
+        alert("Sie müssen erst ein Szenario erstellen, bevor Sie es speichern können.");
+        return false;
+    }
+
     var jsonFile = null;
 
     // find current scenario in all scenarios
-    json = JSON.stringify(authorSystemContent.getScenario(currentScenario));
+    var json = authorSystemContent.getScenario(currentScenario);
+    var jsonLD = JSON.stringify(json ? json.getABoxJSONLD() : {});
 
     // set blob with JSON data
-    var data = new Blob([json], {type: "text/json;charset=utf8"});
+    var data = new Blob([jsonLD], {type: "text/json;charset=utf8"});
 
     // if file will be replaced by another one --> avoid memory leak
     if (jsonFile !== null) {
@@ -31,12 +35,13 @@ function showSaveScenario() {
     // set JSON file
     jsonFile = window.URL.createObjectURL(data);
 
+    var saveScenarioElement = $("#saveScenario");
     // change file name to current scenario name
     saveScenarioElement.children("a")[0].download = currentScenario + ".json";
-
     // add link and open download view
     saveScenarioElement.children("a")[0].href = jsonFile;
 
+
     // show json in new window
     /*var url = "data:text/json;charset=utf8," + encodeURIComponent(JSON.stringify(myAuthorSystem));
      window.open(url, "_blank");
diff --git a/js/authoring/models/aBoxJSONLDModel.js b/js/authoring/models/aBoxJSONLDModel.js
index f02410c..0721fd0 100644
--- a/js/authoring/models/aBoxJSONLDModel.js
+++ b/js/authoring/models/aBoxJSONLDModel.js
@@ -7,11 +7,12 @@
 // formatted and validated with the help of: http://json-ld.org/playground/
 function ABoxJSONLD() {
 
-    // just a placeholder 
+    // a little template for the graph (see below)
     this._typeId = {"@type": "@id"};
 
-    // define the ontology's namespace which will remain just like this
+    // the actual A-Box
     this._jsonLD = {
+        // define the ontology's namespace which will remain just like this
         "@context": {
             "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
             "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
@@ -130,6 +131,7 @@ function ABoxJSONLD() {
                 "@type": "rdfs:Literal"
             }
         },
+        // and the actual content (a list of all JSON-LD individuals)
         "@graph": [
             {
                 "@id": "http://motivate-project.de/ontology/abox.owl",
@@ -142,6 +144,12 @@ function ABoxJSONLD() {
     return this;
 }
 
+// getters
+
+ABoxJSONLD.prototype.getABoxJSONLD = function() {
+    return this._jsonLD;
+};
+
 ABoxJSONLD.prototype.getContext = function () {
     return this._jsonLD["@context"];
 };
@@ -161,6 +169,7 @@ ABoxJSONLD.prototype.containsIndividual = function (namedIndividualJSONLD) {
     for (var i in graph) {
         var individual = graph[i];
 
+        // make sure both have the same keys
         if (Object.keys(individual) != Object.keys(namedIndividualJSONLD))
             continue;
 
diff --git a/js/authoring/models/contextInfoModel.js b/js/authoring/models/contextInfoModel.js
index d796c87..2bbe442 100644
--- a/js/authoring/models/contextInfoModel.js
+++ b/js/authoring/models/contextInfoModel.js
@@ -140,11 +140,9 @@ ContextInformation.prototype.resetAllValues = function() {
 
 /***** JSON-LD formatting *****/
 
-ContextInformation.prototype.getJSONLDGraph = function () {
+ContextInformation.prototype.getJSONLD = function () {
     if (this._chosenValue == "") return false;
 
-    var graphJSONLD = [];
-
     // for this context information, create a new JSON-LD named individual object
     var contextInfoJSONLD = {
         "@id" : "abox:ContextInfo"+uuid4(),
@@ -155,20 +153,22 @@ ContextInformation.prototype.getJSONLDGraph = function () {
     };
 
     // if this context information has parameters, get their JSON-LD named individual objects
-    var parameterJSONLDArray = [];
+    var parameterJSONLDList = [];
+    var parameterReferenceJSONLDList = [];
     for (var i in this._parameters) {
         var parameterJSONLD = this._parameters[i].getJSONLD();
         // add references to these named individuals to the context information individual
-        parameterJSONLDArray.push( {"@id" : parameterJSONLD["@id"]} );
+        parameterReferenceJSONLDList.push( {"@id" : parameterJSONLD["@id"]} );
         // add each parameter individual to the partial ontology graph
-        graphJSONLD.push(parameterJSONLD);
+        parameterJSONLDList.push(parameterJSONLD);
+    }
+    if (parameterReferenceJSONLDList.length == 1)
+        contextInfoJSONLD["kno:hasContextInformationParameter"] = parameterReferenceJSONLDList[0];
+    else if (parameterReferenceJSONLDList.length > 1)
+        contextInfoJSONLD["kno:hasContextInformationParameter"] = parameterReferenceJSONLDList;
+
+    return {
+        contextInfoJSONLD : contextInfoJSONLD,
+        parameterJSONLD : parameterJSONLDList
     }
-    if (parameterJSONLDArray.length == 1)
-        contextInfoJSONLD["kno:hasContextInformationParameter"] = parameterJSONLDArray[0];
-    else if (parameterJSONLDArray.length > 1)
-        contextInfoJSONLD["kno:hasContextInformationParameter"] = parameterJSONLDArray;
-
-    graphJSONLD.push(contextInfoJSONLD);
-
-    return graphJSONLD;
 };
\ No newline at end of file
diff --git a/js/authoring/models/scenarioModel.js b/js/authoring/models/scenarioModel.js
index c884bac..18fc8dc 100644
--- a/js/authoring/models/scenarioModel.js
+++ b/js/authoring/models/scenarioModel.js
@@ -79,7 +79,6 @@ Scenario.prototype.removeConnection = function(connId) {
     }
 };
 
-
 /**
  * Goes through all units of this scenario and gets (copies of) their associated context information items.
  * Chosen values will be reset to "".
@@ -114,4 +113,29 @@ Scenario.prototype.hasContext = function() {
     for (var i in this._units)
         if (this._units[i].getContextData().length != 0) return true;
     return false;
+};
+
+
+/************* JSON-LD formatting *************/
+
+/**
+ * Create an A-Box in JSON-LD for this scenario.
+ * @returns {ABoxJSONLD} The A-Box.
+ */
+Scenario.prototype.getABoxJSONLD = function() {
+    var aBoxJSONLD = new ABoxJSONLD();
+
+    // for each unit ...
+    for (var i in this._units) {
+        // ... get its JSON-LD (a list of JSON-LD named individuals)
+        var unitJSONLDGraph = this._units[i].getJSONLDGraph();
+        // ... add all unique items (individuals) in this list to A-Box graph
+        for (var j in unitJSONLDGraph) {
+            var unitJSONLD = unitJSONLDGraph[j];
+            // prevent unnecessary duplicates
+            if (!aBoxJSONLD.containsIndividual(unitJSONLD))
+                aBoxJSONLD.addToGraph(unitJSONLD);
+        }
+    }
+    return aBoxJSONLD.getABoxJSONLD();
 };
\ No newline at end of file
diff --git a/js/authoring/models/unitModel.js b/js/authoring/models/unitModel.js
index d6b7604..db0b965 100644
--- a/js/authoring/models/unitModel.js
+++ b/js/authoring/models/unitModel.js
@@ -80,18 +80,51 @@ Unit.prototype.removeContextInfoByIndex = function(index) {
 };
 
 
-
+/***** JSON-LD formatting *****/
 
 /**
- * The following function and comment are taken from:
- * https://github.com/University-of-Potsdam-MM/UP.App/blob/bdcd669ae4a75e4666b4bf7c0750a94262e9d5c1/www/js/lib/utils.js
- * (courtesy of Alexander Kiy)
- *
- * Generates a uuid v4. Code is taken from broofas answer in http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
+ * Produce a sub-graph for this unit (array of JSON-LD objects) to be added to JSON-LD
+ * NOTE: Metadata are not yet included in JSON-LD since a matching of this._metadata and T-Box predicates is needed first.
+ * @returns {Array} A sub-graph (array)
  */
-var uuid4 = function() {
-    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
-        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
-        return v.toString(16);
-    });
+Unit.prototype.getJSONLDGraph = function () {
+    // the sub-graph to be returned
+    var graphJSONLD = [];
+
+    // for this unit, create a new JSON-LD named individual object
+    var unitJSONLD = {
+        "@id" : "abox:Unit"+uuid4(),
+        "@type" : [ "kno:LearningUnit", "owl:NamedIndividual" ],
+        "kno:hasLID" : this._uuid,
+        "kno:hasLogicalOperator" : (this._sat == "all") ? "AND" : "OR",
+        // TODO: all relations!!
+        "kno:hasPrerequisite" : [ ]
+        // TODO: metadata according to T-Box
+    };
+
+    // if this unit has context information , get their JSON-LD named individual objects
+    var contextReferenceJSONLDList = [];
+    for (var i in this._contextData) {
+        // get a JSON-LD-containing object for each context item
+        var contextJSONLD = this._contextData[i].getJSONLD();
+
+        // add references to these named JSON-LD individuals to the unit individual
+        contextReferenceJSONLDList.push( {"@id" : contextJSONLD.contextInfoJSONLD["@id"]} );
+
+        // add the context info JSON-LD individual to the partial ontology graph
+        graphJSONLD.push(contextJSONLD.contextInfoJSONLD);
+        // add each parameter JSON-LD individual to the partial ontology graph
+        for (var j in contextJSONLD.parameterJSONLD)
+            graphJSONLD.push(contextJSONLD.parameterJSONLD[j]);
+    }
+    // add context reference(s) to unit JSON-LD individual, if existent
+    if (contextReferenceJSONLDList.length == 1)
+        unitJSONLD["kno:hasMeasurableContextInformation"] = contextReferenceJSONLDList[0];
+    else if (contextReferenceJSONLDList.length > 1)
+        unitJSONLD["kno:hasMeasurableContextInformation"] = contextReferenceJSONLDList;
+
+    // add the unit's JSON-LD individual
+    graphJSONLD.push(unitJSONLD);
+
+    return graphJSONLD;
 };
\ No newline at end of file
diff --git a/js/authoring/utils.js b/js/authoring/utils.js
new file mode 100644
index 0000000..9e025d2
--- /dev/null
+++ b/js/authoring/utils.js
@@ -0,0 +1,19 @@
+/**
+ * Created by elis on 07.01.2016.
+ */
+
+
+
+/**
+ * The following function and comment are taken from:
+ * https://github.com/University-of-Potsdam-MM/UP.App/blob/bdcd669ae4a75e4666b4bf7c0750a94262e9d5c1/www/js/lib/utils.js
+ * (courtesy of Alexander Kiy)
+ *
+ * Generates a uuid v4. Code is taken from broofas answer in http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
+ */
+var uuid4 = function() {
+    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
+        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
+        return v.toString(16);
+    });
+};
\ No newline at end of file
diff --git a/js/main.js b/js/main.js
index 8580220..21847df 100644
--- a/js/main.js
+++ b/js/main.js
@@ -13,7 +13,6 @@ var contextList = new ContextInfoList();
 // will be deleted once refactoring is complete
 //var myAuthorSystem = [];
 var authorSystemContent = new AuthorSystemContent();
-var aBoxJSONLD = new ABoxJSONLD();
 
 // reloading
 var loadedData;
-- 
GitLab