/sandbox/semantic-interaction/trunk/lib/vie2/vie2-latest.debug.js
JavaScript | 1711 lines | 1231 code | 202 blank | 278 comment | 163 complexity | 0bb3189b6f7aaf33834da171cccc5b99 MD5 | raw file
Possible License(s): CC-BY-3.0
Large files files are truncated, but you can click here to view the full file
- // VIE² - Vienna IKS Editable Entities
- // (c) 2011 Sebastian Germesin, IKS Consortium
- // VIE² may be freely distributed under the MIT license.
- // (see LICENSE.txt)
- // For all details and documentation:
- // http://wiki.iks-project.eu/index.php/VIE^2
- (function() {
- // Initial setup
- // -------------
- //
- // The VIE² library is fully contained inside a VIE2 namespace.
- var VIE2 = this.VIE2 = {};
-
- //VIE² is the semantic enrichment layer on top of VIE.
- //Its acronym stands for <b>V</b>ienna <b>I</b>KS <b>E</b>ditable <b>E</b>ntities.
- //With the help of VIE², you can bring entites in your
- //content (aka. semantic lifting) and furthermore interact
- //with this knowledge in a MVC manner - using Backbone JS models
- //and collections. It is important to say that VIE² helps you to
- //automatically annotate data but also let's you enable users
- //to change/add/remove entities and their properties at the users
- //wish.
- //VIE² has two main principles:
- //* Connectors:
- // Connecting VIE² with **backend** services, that
- // can either analyse and enrich the content sent to them (e.g., using
- // Apache Stanbol or Zemanta), can act as knowledge databases (e.g., DBPedia)
- // or as serializer (e.g., RDFa).
- //* Mappings:
- // In a mapping, a web developer can specify a mapping from ontological entities
- // to backbone JS models. The developer can easily add types of entities and
- // also default attributes that are automatically filled with the help of the
- // available connectors.
- // File: util.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- VIE2.Util = {};
- // <strong>VIE2.Util.(haystack, needle)</strong>: Removes the *needle* from the *haystack* array.<br>
- // <code>return void</code>
- VIE2.Util.removeElement = function (haystack, needle) {
- //First we check if haystack is indeed an array.
- if (jQuery.isArray(haystack)) {
- //iterate over the array and check for equality.
- jQuery.each(haystack, function (index) {
- if (haystack[index] === needle) {
- //remove the one element and
- haystack.splice(index, 1);
- //break the iteration.
- return false;
- }
- });
- }
- };
- // <strong>VIE2.Util.isCurie(str)</strong>: Checks whether the given string is a curie.<br>
- // <code>return boolean</code>
- VIE2.Util.isCurie = function (str) {
- return !str.substring(0, 1).match(/^<$/) && !(str.substring(0, 7).match(/^http:\/\/$/));
- }
- // <strong>VIE2.Util.isLiteral(str)</strong>: Checks whether the given string is a literal.<br>
- // <code>return boolean</code>
- VIE2.Util.isLiteral = function (str) {
- try {
- jQuery.rdf.resource(str, {namespaces: VIE2.namespaces.toObj()});
- return false;
- } catch (e) {
- try {
- jQuery.rdf.blank(str, {namespaces: VIE2.namespaces.toObj()});
- return false;
- } catch (f) {
- try {
- jQuery.rdf.literal(str, {namespaces: VIE2.namespaces.toObj()});
- return true;
- } catch (g) {
- return false;
- }
- }
- }
- };
- // <strong>VIE2.Util.isLiteral(str)</strong>: Checks whether the given string is a blank.<br>
- // <code>return boolean</code>
- VIE2.Util.isBlank = function (str) {
- try {
- jQuery.rdf.resource(str, {namespaces: VIE2.namespaces.toObj()});
- return false;
- } catch (h) {
- try {
- jQuery.rdf.blank(str, {namespaces: VIE2.namespaces.toObj()});
- return true;
- } catch (i) {
- return false;
- }
- }
- };
- VIE2.Util.clone = function(src) {
- var newObj = {};
-
- for (k in src) {
- newObj[k] = src[k];
- }
-
- return newObj;
- }
- VIE2.Namespaces = function(namespaces) {
-
- this.namespaces = (namespaces)? namespaces : {};
-
- this.add = function (k, v) {
- //check if we overwrite existing mappings
- if (this.containsKey(k) && v !== this.namespaces[k]) {
- throw "ERROR: Trying to register namespace prefix mapping (" + k + "," + v + ")!" +
- "There is already a mapping existing: '(" + k + "," + this.get(k) + ")'!";
- } else {
- jQuery.each(this.namespaces, function (k1,v1) {
- if (v1 === v && k1 !== k) {
- throw "ERROR: Trying to register namespace prefix mapping (" + k + "," + v + ")!" +
- "There is already a mapping existing: '(" + k1 + "," + v + ")'!";
- }
- });
- }
- this.namespaces[k] = v;
- VIE2.globalCache.prefix(k, v);
- };
-
- this.get = function (k, v) {
- return this.namespaces[k];
- };
-
- this.containsKey = function (k) {
- return (k in this.namespaces);
- };
-
- this.containsValue = function (v) {
- jQuery.each(this.namespaces, function (k1,v1) {
- if (v1 === v) {
- return true;
- }
- });
- return false;
- };
- this.update = function (k, v) {
- this.namespaces[k] = v;
- VIE2.globalCache.prefix(k, v);
- };
-
- this.remove = function (k, v) {
- delete this.namespaces[k];
- delete VIE2.globalCache.databank.namespaces[k];
- };
-
- this.toObj = function () {
- return VIE2.Util.clone(this.namespaces);
- }
- };// File: core.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- (function($, undefined) {
- //VIE² is implmented as a [jQuery UI widget](http://semantic-interaction.org/blog/2011/03/01/jquery-ui-widget-factory/).
- $.widget('VIE2.vie2', {
-
- // default options
- options: {
- entities : []
- },
-
- //<strong>_create()</strong>: The private method **_create():** is called implicitly when
- //calling .vie2(); on any jQuery object.
- _create: function () {
- //automatically scans for xmlns attributes in the **html** element
- //and adds them to the global VIE2.namespaces object
- $.each(jQuery('html').xmlns(), function (k, v) {
- var vStr = v.toString();
- if (!VIE2.namespaces.containsKey(k) && !VIE2.namespaces.containsValue(vStr)) {
- VIE2.namespaces.add(k, vStr);
- }
- });
-
- //automatically scans for xmlns attributes in the **given** element
- //and adds them to the global VIE2.namespaces object
- try {
- $.each(this.element.xmlns(), function(k, v) {
- var vStr = v.toString();
- if (!VIE2.namespaces.containsKey(k) && !VIE2.namespaces.containsValue(vStr)) {
- VIE2.namespaces.add(k, vStr);
- }
- });
- } catch (ex) {
- //needs to be ignored when called on $(document);
- if (this.element.get(0) !== document) {
- VIE2.log("warn", "VIE2.core#create()", "Could not retrieve namespaces from element: '" + e + "'!");
- }
- }
-
- return this;
- },
-
- //<strong>analyze(callback,[options])</strong>: The analyze() method sends the element to all connectors and lets
- //them analyze the content. The connectors' methods are asynchronously called and once all connectors
- //returned the found enrichments in the form of **$.rdf objects**, the *callback* method is
- //executed (in the scope of the callback function, *this* refers to the given element).<br />
- //The returned enrichments are written into the global Cache of VIE² (VIE2.globalCache).<br />
- //Furthermore, each found subject in the returned knowledge is checked whether there is a type-mapping to
- //backbone JS available and if so, the entity is added to the corresponding backbone collection(s).
- //*options* can contain a 'connectors' field. If so, only these connectors will be used
- //for the analysis. If not specified, all connectors are used.
- analyze: function (callback, options) {
- if (!options) { options = {};}
- var that = this;
-
- //analyze() does not actually need a callback method, but it is usually good to use it
- if (callback === undefined) {
- VIE2.log("warn", "VIE2.core#analyze()", "No callback method specified!");
- }
-
- VIE2.log("info", "VIE2.core#analyze()", "Started.");
-
- //as the connectors work asynchronously, we need a queue to listen if all connectors are finished.
- var connectorQueue = [];
- $.each(VIE2.connectors, function () {
- //fill queue of connectors with 'id's to have an overview of running connectors.
- //this supports the asynchronous calls.
- if (options.connectors) {
- if (options.connectors.indexOf(this.id) !== -1) {
- connectorQueue.push(this.id);
- }
- } else {
- connectorQueue.push(this.id);
- }
- });
-
- //iterate over all connectors
- $.each(VIE2.connectors, function () {
- //the connector's success callback method
- var successCallback = function (elem) {
- return function (rdf) {
- VIE2.log("info", "VIE2.core#analyze()", "Received RDF annotation from connector '" + this.id + "'!");
-
- //we add all namespaces to the rdfQuery object.
- //Attention: this might override namespaces that were added by the connector!
- //but needed to keep consistency through VIE².
- $.each(VIE2.namespaces.toObj(), function(k, v) {
- rdf.prefix(k, v);
- });
- rdf.databank.triples().each(function () {
- //add all triples to the global cache!
- VIE2.globalCache.add(this);
- });
-
- //register all subjects as backbone model
- $.each(rdf.databank.subjectIndex, function (subject, v) {
- var subjStr = subject.toString();
- if (that.options.entities.indexOf(subjStr) === -1) {
- that.options.entities.push(subjStr);
- }
-
- if (!VIE.EntityManager.getBySubject(subjStr)) {
- VIE2.log("info", "VIE2.core#analyze()", "Register new entity (" + subjStr + ")!");
-
- VIE2.createEntity({
- id : subjStr
- }, {backend: true});
- } else {
- //inform client(s) that new data is possibly available
- VIE.EntityManager.getBySubject(subjStr).change();
- }
- });
- VIE2.Util.removeElement(connectorQueue, this.id);
- //everytime we receive annotations from each connector, we remove the connector's id from the
- //queue and check whether the queue is empty.
- if (connectorQueue.length === 0) {
- //if the queue is empty, all connectors have successfully returned and we can execute the
- //callback function.
- VIE2.log("info", "VIE2.core#analyze()", "Finished! Global Cache holds now " + VIE2.globalCache.databank.triples().length + " triples!");
- VIE2.log("info", "VIE2.core#analyze()", "Finished! Local element holds now " + that.options.entities.length + " entities!");
- //provide a status field in the callback object: status = {'ok', 'error'};
- if (callback) {
- callback.call(elem);
- }
- }
- };
- } (that.element);
-
- //the connector's error callback method
- var errorCallback = function (reason) {
- VIE2.log("error", "VIE2.core#analyze()", "Connector (" + this.id + ") returned with the following error: '" + reason + "'!");
- VIE2.Util.removeElement(connectorQueue, this.id);
- };
-
- //check if we may need to filter for the connector
- if (options.connectors) {
- if (options.connectors.indexOf(this.id) !== -1) {
- //start analysis with the connector.
- VIE2.log("info", "VIE2.core#analyze()", "Starting analysis with connector: '" + this.id + "'!");
- this.analyze(that.element, {
- success: successCallback,
- error: errorCallback
- });
- }
- else {
- VIE2.log("info", "VIE2.core#analyze()", "Will not use connector " + this.id + " as it is filtered!");
- }
- } else {
- //start analysis with the connector.
- VIE2.log("info", "VIE2.core#analyze()", "Starting analysis with connector: '" + this.id + "'!");
- this.analyze(that.element, {
- success: successCallback,
- error: errorCallback
- });
- }
- });
- },
-
- //<strong>uris()</strong>: Returns a list of all uris, that are within the scope of the current element!
- uris: function () {
- return this.options.entities;
- },
-
- //<strong>addUri()</strong>: Manually adds a URI (string) to the list of entities within the scope of the current element!
- addUri: function (uri) {
- this.options.entities.push(uri);
- },
-
- //<strong>copy(tar)</strong>: Copies all local knowledge to the target element(s).
- //Basically calls: <pre>
- //$(tar).vie2().vie2('option', 'entities', this.options.entities);
- //</pre>
- copy: function (tar) {
- //copy all knowledge from src to target
- var that = this;
- if (!tar) {
- VIE2.log("warn", "VIE2.core#copy()", "Invoked 'copy()' without target element!");
- return;
- }
- VIE2.log("info", "VIE2.core#copy()", "Start.");
- VIE2.log("info", "VIE2.core#copy()", "Found " + this.options.entities.length + " entities for source.");
-
- jQuery(tar).vie2().vie2('option', 'entities', this.options.entities);
- VIE2.log("info", "VIE2.core#copy()", "Finished.");
- VIE2.log("info", "VIE2.core#copy()", "Target element has now " + jQuery(tar).vie2('option', 'entities') + " entities.");
- return this;
- },
-
- //<strong>clear()</strong>: Clears the local entities.
- clear: function () {
- this.options.entities = [];
- return this;
- }
-
- });
- }(jQuery));
- //The global <strong>VIE2 object</strong>. If VIE2 is already defined, the
- //existing VIE2 object will not be overwritten so that the
- //defined object is preserved.
- if (typeof VIE2 === 'undefined' || !VIE2) {
- VIE2 = {};
- }
- //<strong>VIE2.basename</strong>: The basis namespace of the VIE2 schema.
- VIE2.baseNamespace = 'http://schema.org/';
- //<strong>VIE2.namespaces</strong>: This object contains all namespaces known to VIE2.
- //There are currently *one* default namespace:
- // iks -> http://www.iks-ontology.net/
- // owl -> http://www.w3.org/2002/07/owl#
- //Namespaces can be overridden directly using VIE2.namespaces.update(k, v) but
- //are parsed from the <html> tag's xmlns: attribute anyway during initialization.
- VIE2.namespaces = new VIE2.Namespaces({
- 'owl' : 'http://www.w3.org/2002/07/owl#',
- 'xsd' : 'http://www.w3.org/2001/XMLSchema#'
- });
- //<strong>VIE2.globalCache</strong>: The variable **globalCache** stores all knowledge in
- //triples that were retrieved and annotated so far in one *rdfQuery object*. Though it is
- //available via VIE2.globalCache, it is highly discouraged to access it directly.
- VIE2.globalCache = jQuery.rdf({namespaces: VIE2.namespaces.toObj()});
- VIE2.addToCache = function (uri, prop, val) {
- var triple = jQuery.rdf.triple(uri, prop, val, {namespaces: VIE2.namespaces.toObj()});
- VIE2.log("info", "VIE2.addToCache()", "Adding triple to cache!");
- VIE2.log("info", "VIE2.addToCache()", "Global Cache now holds " + VIE2.globalCache.databank.triples().length + " triples!");
- VIE2.globalCache.add(triple);
- VIE2.log("info", "VIE2.addToCache()", "Global Cache now holds " + VIE2.globalCache.databank.triples().length + " triples!");
- };
- //<strong>VIE2.getPropFromCache(parent, uri, prop)</strong>: Retrieve properties from the given
- // *uri* directly from the global Cache.
- VIE2.getPropFromCache = function (parent, uri, prop) {
- //initialize collection
- var Collection = VIE2.ObjectCollection.extend({
- uri : uri,
- property : prop,
- parent : parent
- });
-
- var ret = new Collection();
-
- VIE2.globalCache
- .where(jQuery.rdf.pattern(uri, prop, '?object', {namespaces: VIE2.namespaces.toObj()}))
- .each(function () {
- if (this.object.type) {
- if (this.object.type === 'literal') {
- var inst = VIE2.createLiteral(this.object.representation ? this.object.representation : this.object.value, {lang: this.object.lang, datatype: this.object.datatype, backend:true, silent:true});
- ret.add(inst, {backend:true, silent:true});
- } else if (this.object.type === 'uri' || this.object.type === 'bnode') {
- var entity = VIE.EntityManager.getBySubject(this.object.toString());
- if (entity) {
- ret.add(entity, {backend:true, silent:true});
- }
- else {
- var inst = VIE2.createResource(this.object.value.toString(), {backend:true, silent:true});
- ret.add(inst, {backend:true, silent:true});
- }
- }
- }
- });
-
- return ret;
- };
- VIE2.removeFromCache = function (uri, prop, val) {
- var pattern = jQuery.rdf.pattern(
- uri,
- (prop)? prop : '?x',
- (val)? val : '?y',
- {namespaces: VIE2.namespaces.toObj()});
- VIE2.log("info", "VIE2.removeFromCache()", "Removing triples that match: '" + pattern.toString() + "'!");
- VIE2.log("info", "VIE2.removeFromCache()", "Global Cache now holds " + VIE2.globalCache.databank.triples().length + " triples!");
- VIE2.globalCache
- .where(pattern)
- .remove(pattern);
- VIE2.log("info", "VIE2.removeFromCache()", "Global Cache now holds " + VIE2.globalCache.databank.triples().length + " triples!");
- };
- //<strong>VIE2.clearCache()</strong>: Static method to clear the global Cache.
- VIE2.clearCache = function () {
- VIE2.globalCache = jQuery.rdf({namespaces: VIE2.namespaces.toObj()});
- };
- //<strong>VIE2.lookup(uri, props, callback)</strong>: The query function supports querying for properties. The uri needs
- //to be of type <code>jQuery.rdf</code> object or a simple string and the property is either an array of strings
- //or a simple string. The function iterates over all connectors that have <code>query()</code>
- //implemented and collects data in an object.
- //The callback retrieves an object with the properties as keys and an array of results as their corresponding values.
- VIE2.lookup = function (uri, props, callback) {
- VIE2.log("info", "VIE2.lookup()", "Start ('" + uri + "', '" + props + "')!");
- if (uri === undefined || typeof uri !== 'string' || props === undefined) {
- VIE2.log("warn", "VIE2.lookup()", "Invoked 'lookup()' with wrong/undefined argument(s)!");
- if (callback) {
- callback.call(uri, ret);
- }
- return;
- }
-
- if (!jQuery.isArray(props)) {
- VIE2.lookup(uri, [ props ], callback);
- return;
- }
-
- //initialize the returning object
- var ret = {};
- for (var i=0; i < props.length; i++) {
- ret[props[i]] = [];
- }
-
- var connectorQueue = [];
- jQuery.each(VIE2.connectors, function () {
- //fill queue of connectors with 'id's to have an overview of running connectors.
- //this supports the asynchronous calls.
- connectorQueue.push(this.id);
- });
-
- //look up for properties in the connectors that
- //implement/overwrite the query() method
- jQuery.each(VIE2.connectors, function () {
- var c = function (uri, ret, callback) {
- return function (data) {
- try {
- VIE2.log("info", "VIE2.lookup()", "Received query information from connector '" + this.id + "' for uri '" + uri + "'!");
- jQuery.each(data, function (k, v) {
- for (var i = 0; i < v.length; i++) {
- var triple = jQuery.rdf.triple(uri, k, v[i], {namespaces: VIE2.namespaces.toObj()});
- VIE2.globalCache.add(triple);
- }
- });
- VIE2.Util.removeElement(connectorQueue, this.id);
- if (connectorQueue.length === 0) {
- //if the queue is empty, all connectors have successfully returned and we can call the
- //callback function.
- jQuery.each(ret, function(k){
- VIE2.globalCache.where(uri + ' ' + k + ' ?x').each(function(){
- var valStr = this.x.toString();
- if (ret[k].indexOf(valStr) === -1) {
- ret[k].push(valStr);
- }
- });
- });
- VIE2.log("info", "VIE2.lookup()", "Global Cache now holds " + VIE2.globalCache.databank.triples().length + " triples!");
- if (callback) {
- callback.call(uri, ret);
- }
- }
- } catch (e) {
- }
- };
- }(uri, ret, callback);
- this.query(uri, props, c);
- });
- };
- //<strong>VIE2.serialize</strong>: TODO document me
- VIE2.serialize = function (model, options) {
-
- if (!options)
- options = {};
-
- VIE2.log("info", "VIE2.Backbone#serialize(" + model.get('id') + ")", "Start serialization!");
-
- var connectorQueue = [];
- jQuery.each(VIE2.connectors, function(){
- //fill queue of connectors with 'id's to have an overview of running connectors.
- //this supports the asynchronous calls.
- if (options.connectors) {
- if (options.connectors.indexOf(this.id) !== -1) {
- connectorQueue.push(this.id);
- }
- }
- else {
- connectorQueue.push(this.id);
- }
- });
-
- //iterate over all connectors
- jQuery.each(VIE2.connectors, function() {
- //the connector's success callback method
- var successCallback = function(){
- VIE2.log("info", "VIE2.serialize(" + model.get('id') + ")", "Successfully serialized the annotation!");
- VIE2.Util.removeElement(connectorQueue, this.id);
- };
-
- var errorCallback = function(reason) {
- VIE2.log("error", "VIE2.serialize(" + model.get('id') + ")", "");
- VIE2.Util.removeElement(connectorQueue, this.id);
- };
-
- //check if we may need to filter for the connector
- if (options.connectors) {
- if (options.connectors.indexOf(this.id) !== -1) {
- //start analysis with the connector.
- VIE2.log("info", "VIE2.serialize(" + model.get('id') + ")", "Starting serialization with connector: '" + this.id + "'!");
- if (model instanceof VIE2.Entity) {
- var triple = model.get('a').at(0).tojQueryRdfTriple(); //TODO!
- } else {
- var triple = model.tojQueryRdfTriple(); //TODO!
- }
-
- this.serialize(triple, jQuery.extend(options, {
- success: successCallback,
- error: errorCallback
- }));
- }
- else {
- VIE2.log("info", "VIE2.serialize(" + model.get('id') + ")", "Will not use connector " + this.id + " as it is filtered!");
- }
- }
- else {
- //start analysis with the connector.
- VIE2.log("info", "VIE2.serialize(" + model.get('id') + ")", "Starting serialization with connector: '" + this.id + "'!");
- //TODO: toTriple(this);
- this.serialize(this, jQuery.extend(options, {
- success: successCallback,
- error: errorCallback
- }));
- }
- });
- };
- //<strong>VIE2.types</strong>: Contains for all registered types (type.id is the key), the
- //following items:<br/>
- //* VIE2.types[id].type -> the type object itself
- //* VIE2.types[id].collection -> the Backbone.js collection, that has the type registered.
- VIE2.types = {};
- //<strong>VIE2.registerType(type)</strong>: Static method to register a type (is automatically called
- //during construction of type class. This allocates an object in *VIE2.types[type.id]*.
- VIE2.registerType = function (type) {
- //first check if there is already
- //a type with 'type.id' registered
- if (!VIE2.types[type.id]) {
-
- var Collection = VIE2.EntityCollection.extend({model: VIE2.Entity});
-
- VIE2.types[type.id] = type;
-
- //Person -> VIE2.Persons
- VIE2[type.sid + "s"] = new Collection();
-
- //trigger filling of collections!
- for (var i = 0; i < VIE2.entities.length; i++) {
- VIE2.entities.at(i).searchCollections();
- }
- } else {
- VIE2.log("warn", "VIE2.registerType()", "Did not register type, as there is" +
- "already a type with the same id registered.");
- }
- };
- VIE2.getType = function (typeId) {
-
- if (typeId.indexOf('<') === 0) {
- return VIE2.types[typeId];
- }
- else if (typeId.indexOf(VIE2.baseNamespace) === 0) {
- return VIE2.getType('<' + typeId + '>');
- }
- else {
- return VIE2.getType('<' + VIE2.baseNamespace + typeId + '>');
- }
- return undefined;
- }
- //<strong>VIE2.unregisterType(typeId)</strong>: Unregistering of types.
- // There is currently no usecase for that, but it wasn't that hard to implement ;)
- VIE2.unregisterType = function (typeId) {
- delete VIE2.types[typeId];
- delete VIE2[typeId + "s"];
- };
- //<strong>VIE2.connectors</strong>: Static object of all registered connectors.
- VIE2.connectors = {};
- //<strong>VIE2.registerConnector(connector)</strong>: Static method to register a connector (is automatically called
- //during construction of connector class. If set, inserts connector-specific namespaces to the known Caches.
- VIE2.registerConnector = function (connector) {
- //first check if there is already
- //a connector with 'connector.id' registered
- if (!VIE2.connectors[connector.id]) {
- VIE2.connectors[connector.id] = connector;
- } else {
- VIE2.log("warn", "VIE2.registerConnector()", "Did not register connector, as there is" +
- "already a connector with the same id registered.");
- }
- };
- //<strong>VIE2.unregisterConnector(connectorId)</strong>: Unregistering of connectors. There is currently
- //no usecase for that, but it wasn't that hard to implement ;)
- VIE2.unregisterConnector = function (connectorId) {
- VIE2.connectors[connector.id] = undefined;
- };
- VIE2.logLevels = ["info", "warn", "error"];
- //<strong>VIE2.log(level, component, message)</strong>: Static convenience method for logging.
- VIE2.log = function (level, component, message) {
- if (VIE2.logLevels.indexOf(level) > -1) {
- switch (level) {
- case "info":
- console.info([component, message]);
- break;
- case "warn":
- console.warn([component, message]);
- break;
- case "error":
- console.error([component, message]);
- break;
- }
- }
- };
- // File: collection.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- //just for convenience, should be removed in a later revision
- VIE.EntityManager.initializeCollection();
- //<strong>VIE2.EntityCollection</strong>: TODO: document me
- VIE2.EntityCollection = VIE.RDFEntityCollection.extend({
-
- //overwrite the internal _add method
- _add: function (model, opts) {
- if (!opts) { opts = {};}
-
- if (this.get(model.get('id'))) {
- return;
- }
-
- if (!model.isEntity()) {
- return;
- }
-
- VIE.RDFEntityCollection.prototype._add.call(this, model, opts);
-
- //if the annotation does *not* come from the analyze() method
- //it comes from the user and hence,
- //we need to add the subject to the internal triple store.
- if (!opts.backend) {
- var type = model.get('a');
- if (type.length > 0) {
- type = type.at(0).value();
- } else {
- type = VIE2.getType('Thing').id //TODO: hack!
- }
- var triple = jQuery.rdf.triple(
- model.get('id'),
- 'a',
- type,
- {namespaces: VIE2.namespaces.toObj()}
- );
- VIE2.globalCache.add(triple);
- }
- },
-
- _remove: function (model, opts) {
- if (!opts) { opts = {};}
- if (model) {
- //when removing the model from this collection, that means
- //that we remove all corresponding data from the cache as well.
- if (VIE2.entities === this) {
- VIE2.removeFromCache(model.get('id'));
- delete VIE2.globalCache.databank.subjectIndex[model.get('id')]; //HACK: rdfQuery does not remove an entity from its internal DB when no other triples are present
- //also remove from all other collections!
- jQuery.each(VIE2.mappings, function(k, v){
- v.collection.remove(model);
- });
-
- VIE.EntityManager.entities.remove(model, opts);
- model.destroy();
- }
- VIE.RDFEntityCollection.prototype._remove.call(this, model, opts);
- }
- }
- });
- //<strong>VIE2.entities</strong>: Is a global Backbone JS Collection
- //which stores all models of all known entities.
- VIE2.entities = new VIE2.EntityCollection();
- //<strong>VIE2.ObjectCollection</strong>: TODO: document me
- VIE2.ObjectCollection = Backbone.Collection.extend({
-
- _add: function (model, opts) {
- //TODO: propagate event to parent model
- if (!opts) { opts = {};}
-
- //adding a back-reference to the model
- model.collection = this;
- Backbone.Collection.prototype._add.call(this, model, opts);
-
- if (!opts.backend) {
- var triple = jQuery.rdf.triple(
- this.uri,
- this.property,
- model.tojQueryRdf(),
- {namespaces: VIE2.namespaces.toObj()}
- );
- VIE2.globalCache.add(triple);
- if (this.parent) {
- this.parent.change();
- this.parent.trigger('change:' + this.property);
- }
- }
- },
-
- _remove: function (model, opts) {
- if (model) {
- //remove corresponding triples
- VIE2.removeFromCache(this.uri, this.property, model.tojQueryRdf());
-
- Backbone.Collection.prototype._remove.call(this, model, opts);
-
- //update parent entity
- this.parent.trigger('change:' + this.property);
- }
- },
-
- getByValue: function (value, opts) {
- if (!opts) { opts = {}; }
-
- var found;
- $.each(this.models, function (i, model) {
- if (model.get('value') === value) {
- if (opts.lang) {
- if (opts.lang === model.get('lang')) {
- found = model;
- return false;
- }
- } else if (opts.datatype) {
- if (opts.datatype === model.get('datatype')) {
- found = model;
- return false;
- }
- } else {
- found = model;
- return false;
- }
- }
- });
-
- return found;
- }
- });
- // File: model.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- //<strong>VIE2.Entity</strong>: The parent backbone entity class for all other entites.
- //Inherits from VIE.RDFEntity.
- VIE2.Entity = VIE.RDFEntity.extend({
-
- initialize: function (attrs, opts) {
- //if the type has changed, we need to search through the
- //types if the model needs to be inserted.
- this.bind('change:a', this.searchCollections);
-
- if (!opts) { opts = {};}
-
- if (!opts.backend) {
- for (var attr in attrs) {
- var val = attrs[attr];
- if (attr !== 'id') {
- var valArr;
- if (!jQuery.isArray(val)) {
- valArr = [ val ];
- } else {
- valArr = val;
- }
- for (var i = 0; i < valArr.length; i++) {
- var triple = jQuery.rdf.triple(this.get('id'), attr, valArr[i], {
- namespaces: VIE2.namespaces.toObj()
- });
- VIE2.globalCache.add(triple);
- }
- }
- }
- }
-
- //in any case, we query all connectors for the types of the entity.
- VIE2.lookup(this.get('id'), ['a', 'sameAs'], function (m) {
- return function () {
- m.trigger('change:a');
- m.trigger('change:sameAs');
- };
- }(this));
- },
-
- searchCollections: function () {
- var self = this;
-
- var types = VIE2.getPropFromCache(this, this.get('id'), 'a');
-
- for (var t = 0; t < types.length; t++) {
- var type = VIE2.getType(types.at(t).value());
- if (type) {
- if (!VIE2[type.sid + "s"].get(self.id)) {
- VIE2[type.sid + "s"].add(self, {backend: true});
- VIE2.log("info", "VIE2.Entity.searchCollections()", "Added entity '" + self.get('id') + "' to collection of type '" + type.id + "'!");
- }
- }
- }
- },
- //overwritten to directly access the global Cache
- get: function (attr) {
- if (attr === 'id') {
- return VIE.RDFEntity.prototype.get.call(this, attr);
- }
- return VIE2.getPropFromCache(this, this.get('id'), attr);
- },
-
- isEntity: function () {
- return true;
- }
- });
- VIE2.createEntity = function (type, attrs, opts) {
- if (!type) {
- type = VIE2.getType("Thing");
- } else if (typeof type === 'string') {
- type = VIE2.getType(type);
- }
- if (!attrs) {
- attrs = {};
- }
- if (!opts) {
- opts = {};
- }
- if (!('id' in attrs)) {
- attrs.id = $.rdf.blank('[]').toString();
- }
-
- //setting the type of the entity
- attrs.a = type.id;
-
- //create the model
- var model = new VIE2.Entity(attrs, opts);
-
- //automatically adds model to global VIE2.entities bucket
- VIE2.entities.add(model, opts);
-
- return model;
- };
- VIE2.Object = Backbone.Model.extend({
-
- initialize: function (attrs, opts) {
- if (!opts) { opts = {};}
-
- this.isLiteral = (opts.isLiteral)? opts.isLiteral : false;
- },
-
- set: function (attrs, opts) {
- if (!opts) { opts = {};}
- if (!attrs) return this;
-
- var oldValue = this.attributes['value'];
- var newValue = attrs['value'];
-
- if (oldValue !== undefined && oldValue !== newValue) {
- if (this.collection) {
- //remove old triple, add new triple!
- VIE2.removeFromCache(this.collection.uri,
- this.collection.property,
- oldValue);
-
- var triple = jQuery.rdf.triple(
- this.collection.uri,
- this.collection.property,
- this.tojQueryRdf(newValue),
- {namespaces: VIE2.namespaces.toObj()});
- VIE2.globalCache.add(triple);
-
- this.collection.parent.trigger('change:a');
- }
- }
- return Backbone.Model.prototype.set.call(this, attrs, opts);
- },
-
- tojQueryRdf: function (val) {
- if (this.isLiteral) {
- return this._tojQueryRdfLit(val);
- } else {
- return this._tojQueryRdfRes(val);
- }
- },
-
- _tojQueryRdfLit: function (val) {
- var lang = (this.get('lang')) ? this.get('lang') : undefined;
- var datatype = (this.get('datatype')) ? this.get('datatype') : undefined;
-
- if (lang !== undefined && datatype !== undefined) {
- datatype = undefined;
- }
-
- var val = (val)? val : this.get('value');
-
- var lit = jQuery.rdf.literal(
- val, {
- namespaces: VIE2.namespaces.toObj(),
- datatype: datatype,
- lang: lang
- });
- return lit;
- },
-
- _tojQueryRdfRes: function (val) {
- val = (val)? val : this.get('value');
-
- if (val.indexOf('_:') === 0) {
- return jQuery.rdf.blank(val);
- } else {
- return jQuery.rdf.resource(
- val, {
- namespaces: VIE2.namespaces.toObj()
- });
- }
- },
-
- tojQueryRdfTriple: function () {
- var triple = jQuery.rdf.triple(this.collection.uri + " " + this.collection.property + " " + this.tojQueryRdf().toString(), {
- namespaces: VIE2.namespaces.toObj()
- });
-
- return triple;
- },
-
- //for convenience
- value: function () {
- return this.get('value');
- },
- //for convenience
- datatype: function () {
- return this.get('datatype');
- },
- //for convenience
- lang: function () {
- return this.get('lang');
- },
-
- isResource: function () {
- return this.get('isResource');
- },
-
- isLiteral: function () {
- return this.get('isLiteral');
- },
-
- isEntity: function () {
- return false;
- }
- });
- VIE2.createLiteral = function (value, opts) {
- if (!opts) { opts = {};}
- return new VIE2.Object({
- 'value': value,
- isResource: false,
- lang: opts.lang,
- datatype: opts.datatype,
- }, jQuery.extend(opts, {isLiteral: true}));
- };
- VIE2.createResource = function (value, opts) {
- if (!opts) { opts = {};}
- return new VIE2.Object({
- 'value': (value.indexOf('<') === 0 || value.indexOf('_:') === 0)? value : '<' + value + '>',
- isLiteral: false,
- isResource: true
- }, jQuery.extend(opts, {isLiteral: false}));
- };
- // File: connector.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- //The Connector class.
- //So far, a connector has two main functionalities:
- //1. analyze: Applies semantic lifting of the passed object
- //2. query: Queries for properties of the given entity uri
- //A connector needs an **id** of type string and an optional
- //options object. The only option that is used in VIE² so far
- //is options['namespaces'], which adds connector-specific
- //namespaces to VIE². However, you may add other options,
- //specific for this connector here.
- //After registration, they can be changed with:
- //<pre>
- // VIE2.connectors['<id>'].options({...});
- //</pre>
- VIE2.Connector = function(id, options) {
- //A connector needs an id of type string.
- if (id === undefined || typeof id !== 'string') {
- throw "The connector constructor needs an 'id' of type 'string'!";
- }
-
- this.id = id;
- this._options = (options)? options : {};
-
- if (this._options.namespaces) {
- jQuery.each(this._options.namespaces, function (k, v) {
- VIE2.namespaces.add(k, v);
- });
- }
- //registers the connector within VIE². Also adds the given namespaces
- //to the global cache in VIE².
- VIE2.registerConnector(this);
- };
- //setter and getter for options
- VIE2.Connector.prototype.options = function(values) {
- if (typeof values === 'string') {
- //return the values
- return this._options[values];
- }
- else if (typeof values === 'object') {
- //extend options
- jQuery.extend(true, this._options, values);
- } else {
- //get options
- return this._options;
- }
- };
- //TODO: document me
- VIE2.Connector.prototype.analyze = function (object, options) {
- //VIE2.log("info", "VIE2.Connector(" + this.id + ")#analyze()", "Not overwritten!");
- if (options && options.success) {
- options.success.call(this, jQuery.rdf());
- }
- };
- //TODO: document me
- VIE2.Connector.prototype.query = function (uri, properties, callback) {
- //VIE2.log("info", "VIE2.Connector(" + this.id + ")#query()", "Not overwritten!");
- callback.call(this, {});
- };
- VIE2.Connector.prototype.serialize = function (rdf, options) {
- //VIE2.log("info", "VIE2.Connector(" + this.id + ")#serialize()", "Not overwritten!");
- if (options && options.success) {
- options.success.call(this, {});
- }
- };// File: attribute.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- // An <code>Attribute</code> is a format to map ontological entity attributes into the
- // VIE² world - and hence, Backbone.js models.
- VIE2.Attribute = function(type, id, datatype, namespaces) {
- if (type && typeof type === 'string') {
- type = VIE2.getType(type);
- }
- if (type === undefined) {
- throw "The attribute constructor needs a 'type'!";
- }
- if (id === undefined) {
- throw "The attribute constructor needs an 'id'!";
- }
- if (typeof id !== 'string') {
- throw "The attribute constructor needs an 'id' of type 'string'!";
- }
- if (!datatype) {
- throw "The attribute constructor needs a 'datatype' of type 'string', e.g., 'Thing'!";
- }
-
- this.id = (VIE2.baseNamespace)? '<' + VIE2.baseNamespace + id + '>' : id;
- this.sid = id;
- this.type = type;
-
- this.datatype = datatype;
-
- //add given namespaces to VIE²'s namespaces
- this.namespaces = (namespaces)? namespaces : {};
-
- this.validateEntityType = function (type) {
- return type.id === this.id;
- };
- };// File: type.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- // A <code>Type</code> is a format to map ontological entity types into the VIE² world
- // - and hence, Backbone.js models.
- VIE2.Type = function(id, parent, attrs, namespaces) {
- if (id === undefined) {
- throw "The type constructor needs an 'id'!";
- }
- if (typeof id !== 'string') {
- throw "The type constructor needs an 'id' of type 'string'!";
- }
- if (parent !== undefined && typeof parent !== 'string') {
- throw "The type constructor needs a 'parent' of type 'string', e.g., 'Thing'!";
- }
- if (attrs === undefined) {
- throw "The type constructor needs 'attributes'!";
- }
-
- if (VIE2.getType(id)) {
- // singleton!
- return VIE2.getType(id);
- }
-
- this.id = (VIE2.baseNamespace)? '<' + VIE2.baseNamespace + id + '>' : id;
- this.sid = id;
-
- this._parent = parent;
-
- this._children = [];
-
- //add given namespaces to VIE²'s namespaces
- this.namespaces = (namespaces)? namespaces : {};
- jQuery.each(this.namespaces, function (k, v) {
- VIE2.namespaces.add(k, v);
- });
-
- // allocate attributes
- this._attrs = attrs;
-
- this.listAttrs = function (targetType) {
- var attrs = [];
- for (var a = 0; a < this._attrs.length; a++) {
- var aId = this._attrs[a].id;
- var dt = (VIE2.getType(this._attrs[a].datatype))? VIE2.getType(this._attrs[a].datatype) : this._attrs[a].datatype;
- if (!targetType || VIE2.getType(targetType).id === dt.id) {
- attrs.push(new VIE2.Attribute(this, aId, dt, this.namespaces));
- }
- }
-
- if (this.getParent()) {
- var parentAttrs = this.getParent().listAttrs(targetType);
- for (var i = 0; i < parentAttrs.length; i++) {
- var contains = false;
- for (var j = 0; j < attrs.length; j++) {
- if (attrs[j].id === parentAttrs[i].id) {
- contains = true;
- }
- }
- if (!contains) {
- attrs.push(parentAttrs[i]);
- }
- }
- }
- return attrs;
- };
-
- this.getAttr = function (aId) {
- var attrs = this.listAttrs();
- for (var a = 0; a < attrs.length; a++) {
- if (attrs[a].id === aId || attrs[a].sid === aId) {
- return attrs[a];
- }
- }
- return undefined;
- };
-
- this.getParent = function () {
- //in case the parent was not resolved during init
- if (typeof this._parent === 'string') {
- this._parent = VIE2.getType(this._parent);
- }
- return this._parent;
- };
-
- if (this.getParent()) {
- this.getParent()._children.push(this);
- };
-
- this.isTypeOf = function (type) {
- var searchFor = type;
- if (typeof type === 'string') {
- searchFor = VIE2.getType(type);
- }
-
- if (this.id === searchFor.id) {
- return true;
- }
- if (this.getParent() !== undefined) {
- return this.getParent().isTypeOf(searchFor);
- }
- return false;
- };
- this.getHierarchyObject = function () {
- var obj = {id : this.id, children: []};
- for (var c = 0; c < this._children.length; c++) {
- obj.children.push(this._children[c].getHierarchyObject());
- }
- return obj;
- }
-
- //automatically registers the mapping in VIE^2.
- VIE2.registerType(this);
-
- return this;
- };// File: person.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- new VIE2.Type (
- 'DataType', //the id of the mapping
- undefined,
- [
- {'id' : 'value',
- 'datatype' : 'xsd:anyType'
- }
- ],
- { //the used namespaces, these can be given here, or placed directly into the HTML document's xmlns attribute.
- 'xsd' : 'http://www.w3.org/2001/XMLSchema#'
- }
- );
- // File: person.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- new VIE2.Type (
- 'Boolean', //the id of the mapping
- 'DataType',
- [
- {'id' : 'value',
- 'datatype' : 'xsd:boolean'
- }
- ],
- { //the used namespaces, these can be given here, or placed directly into the HTML document's xmlns attribute.
- 'xsd' : 'http://www.w3.org/2001/XMLSchema#'
- }
- );
- // File: person.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- new VIE2.Type (
- 'Number', //the id of the mapping
- 'DataType',
- [
- {'id' : 'value',
- 'datatype' : 'xsd:anySimpleType'
- }
- ],
- { //the used namespaces, these can be given here, or placed directly into the HTML document's xmlns attribute.
- 'xsd' : 'http://www.w3.org/2001/XMLSchema#'
- }
- );
- // File: person.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- new VIE2.Type (
- 'Date', //the id of the mapping
- 'DataType',
- [
- {'id' : 'value',
- 'datatype' : 'xsd:date'
- }
- ],
- { //the used namespaces, these can be given here, or placed directly into the HTML document's xmlns attribute.
- 'xsd' : 'http://www.w3.org/2001/XMLSchema#'
- }
- );
- // File: person.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- new VIE2.Type (
- 'Text', //the id of the mapping
- 'DataType',
- [
- {'id' : 'value',
- 'datatype' : 'xsd:string'
- }
- ],
- { //the used namespaces, these can be given here, or placed directly into the HTML document's xmlns attribute.
- 'xsd' : 'http://www.w3.org/2001/XMLSchema#'
- }
- );
- // File: person.js
- // Author: <a href="mailto:sebastian.germesin@dfki.de">Sebastian Germesin</a>
- //
- new VIE2.Type (
- 'Float', //the id of the mapping
- 'Number',
- [
- {'id' : 'value',
- 'datatype' : 'xsd:float'
- }
- ],
- { //the used namespaces, these can be given here, or placed directly into the HTML document's xmlns attribute.
- 'xsd' : 'http://www.w3.org/2001/XMLSchema#'
- }
- );
- // File: person.js
- // Auth…
Large files files are truncated, but you can click here to view the full file