You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@clerezza.apache.org by re...@apache.org on 2015/04/18 11:48:53 UTC
[1/7] clerezza git commit: CLEREZZA-987: loging execptions
Repository: clerezza
Updated Branches:
refs/heads/master 27c750e0b -> b584894e5
CLEREZZA-987: loging execptions
Project: http://git-wip-us.apache.org/repos/asf/clerezza/repo
Commit: http://git-wip-us.apache.org/repos/asf/clerezza/commit/51eade19
Tree: http://git-wip-us.apache.org/repos/asf/clerezza/tree/51eade19
Diff: http://git-wip-us.apache.org/repos/asf/clerezza/diff/51eade19
Branch: refs/heads/master
Commit: 51eade1955411b682891e1f555331d931c1a3ccb
Parents: 27c750e
Author: Reto Gmuer <re...@apache.org>
Authored: Sat Apr 18 09:08:01 2015 +0000
Committer: Reto Gmuer <re...@apache.org>
Committed: Sat Apr 18 09:48:37 2015 +0000
----------------------------------------------------------------------
.../platform/typerendering/GenericGraphNodeMBW.java | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/clerezza/blob/51eade19/platform/typerendering/platform.typerendering.core/src/main/java/org/apache/clerezza/platform/typerendering/GenericGraphNodeMBW.java
----------------------------------------------------------------------
diff --git a/platform/typerendering/platform.typerendering.core/src/main/java/org/apache/clerezza/platform/typerendering/GenericGraphNodeMBW.java b/platform/typerendering/platform.typerendering.core/src/main/java/org/apache/clerezza/platform/typerendering/GenericGraphNodeMBW.java
index 4ed89ef..7a4e4a5 100644
--- a/platform/typerendering/platform.typerendering.core/src/main/java/org/apache/clerezza/platform/typerendering/GenericGraphNodeMBW.java
+++ b/platform/typerendering/platform.typerendering.core/src/main/java/org/apache/clerezza/platform/typerendering/GenericGraphNodeMBW.java
@@ -149,8 +149,13 @@ public class GenericGraphNodeMBW implements MessageBodyWriter<GraphNode> {
Map<String, Object> sharedRenderingValues = new HashMap<String, Object>();
ResultDocModifier.init();
if (!(rendererMediaType.getType().equals("application") && rendererMediaType.getSubtype().equals("xhtml+xml"))) {
- httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, rendererMediaType);
- renderer.render(node, getUserContext(), mode, uriInfo, headers, httpHeaders, sharedRenderingValues, entityStream);
+ try {
+ httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, rendererMediaType);
+ renderer.render(node, getUserContext(), mode, uriInfo, headers, httpHeaders, sharedRenderingValues, entityStream);
+ } catch (RuntimeException ex) {
+ logger.error("error rendering GraphNode", ex);
+ throw ex;
+ }
} else {
final MediaType mediaTypeWithCharset = MediaType.valueOf(MediaType.APPLICATION_XHTML_XML+";charset=UTF-8");
httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, mediaTypeWithCharset);
[7/7] clerezza git commit: CLEREZZA-829:added test to make sure
datatype is read correctly
Posted by re...@apache.org.
CLEREZZA-829:added test to make sure datatype is read correctly
Project: http://git-wip-us.apache.org/repos/asf/clerezza/repo
Commit: http://git-wip-us.apache.org/repos/asf/clerezza/commit/b584894e
Tree: http://git-wip-us.apache.org/repos/asf/clerezza/tree/b584894e
Diff: http://git-wip-us.apache.org/repos/asf/clerezza/diff/b584894e
Branch: refs/heads/master
Commit: b584894e535bcdd3df064b02bf45f99258ddfd02
Parents: 83342fb
Author: Reto Gmuer <re...@apache.org>
Authored: Sat Apr 18 09:48:20 2015 +0000
Committer: Reto Gmuer <re...@apache.org>
Committed: Sat Apr 18 09:48:40 2015 +0000
----------------------------------------------------------------------
.../rdf/jena/parser/JenaParserProviderTest.java | 12 ++++++++++++
.../org/apache/clerezza/rdf/jena/parser/test-05.nt | 2 ++
2 files changed, 14 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/clerezza/blob/b584894e/rdf/jena/parser/src/test/java/org/apache/clerezza/rdf/jena/parser/JenaParserProviderTest.java
----------------------------------------------------------------------
diff --git a/rdf/jena/parser/src/test/java/org/apache/clerezza/rdf/jena/parser/JenaParserProviderTest.java b/rdf/jena/parser/src/test/java/org/apache/clerezza/rdf/jena/parser/JenaParserProviderTest.java
index 219c54e..ff777de 100644
--- a/rdf/jena/parser/src/test/java/org/apache/clerezza/rdf/jena/parser/JenaParserProviderTest.java
+++ b/rdf/jena/parser/src/test/java/org/apache/clerezza/rdf/jena/parser/JenaParserProviderTest.java
@@ -27,6 +27,8 @@ import org.apache.clerezza.rdf.core.serializedform.ParsingProvider;
import org.apache.clerezza.commons.rdf.Graph;
import org.apache.clerezza.commons.rdf.ImmutableGraph;
import org.apache.clerezza.commons.rdf.IRI;
+import org.apache.clerezza.commons.rdf.Literal;
+import org.apache.clerezza.commons.rdf.Triple;
import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph;
@@ -49,6 +51,16 @@ public class JenaParserProviderTest {
ImmutableGraph graphFromTurtle = parse(provider, turtleIn, "text/turtle", null);
Assert.assertEquals(graphFromNTriples, graphFromTurtle);
}
+
+ @Test
+ public void testNTriplesDataType() {
+ ParsingProvider provider = new JenaParserProvider();
+ InputStream nTriplesIn = getClass().getResourceAsStream("test-05.nt");
+ ImmutableGraph graphFromNTriples = parse(provider, nTriplesIn, "application/n-triples", null);
+ Assert.assertEquals(2, graphFromNTriples.size());
+ Triple t1 = graphFromNTriples.filter(null, new IRI("http://discobits.org/ontology#infoBit"), null).next();
+ Assert.assertEquals(new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral"), ((Literal)t1.getObject()).getDataType());
+ }
/*
* comparing result from nt and rdf/xml parsing,
http://git-wip-us.apache.org/repos/asf/clerezza/blob/b584894e/rdf/jena/parser/src/test/resources/org/apache/clerezza/rdf/jena/parser/test-05.nt
----------------------------------------------------------------------
diff --git a/rdf/jena/parser/src/test/resources/org/apache/clerezza/rdf/jena/parser/test-05.nt b/rdf/jena/parser/src/test/resources/org/apache/clerezza/rdf/jena/parser/test-05.nt
new file mode 100644
index 0000000..0ecd1ae
--- /dev/null
+++ b/rdf/jena/parser/src/test/resources/org/apache/clerezza/rdf/jena/parser/test-05.nt
@@ -0,0 +1,2 @@
+<http://localhost:8080/getting-started/shell/content-el/3-title> <http://discobits.org/ontology#infoBit> "Commands and Expressions"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral> .
+<http://localhost:8080/getting-started/shell/content-el/3-title> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://discobits.org/ontology#XHTMLInfoDiscoBit> .
\ No newline at end of file
[3/7] clerezza git commit: CLEREZZA-829: using turtle-sections to
have the original version without any changes in HTML-literals
Posted by re...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/98a83b69/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/rdf-ext.js
----------------------------------------------------------------------
diff --git a/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/rdf-ext.js b/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/rdf-ext.js
new file mode 100644
index 0000000..d32c520
--- /dev/null
+++ b/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/rdf-ext.js
@@ -0,0 +1,19324 @@
+(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
+'use strict';
+
+
+var init = function (rdf) {
+ var cf = {};
+
+ cf.options = {
+ convertStringUrls: true
+ };
+
+ cf.urlRegEx = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
+
+ var node = function (value) {
+ if (Array.isArray(value)) {
+ return value.map(function (item) {
+ return node(item);
+ });
+ }
+
+ if (typeof value === 'object' && 'interfaceName' in value) {
+ return value;
+ }
+
+ if (typeof value === 'string') {
+ if (cf.options.convertStringUrls && cf.urlRegEx.test(value)) {
+ return rdf.createNamedNode(value);
+ } else {
+ return rdf.createLiteral(value);
+ }
+ } else if (typeof value === 'number') {
+ return rdf.createLiteral(value + '');
+ } else {
+ throw 'unknown type';
+ }
+ };
+
+ var inArray = function (node, array) {
+ return array.some(function (otherNode) {
+ return otherNode.equals(node);
+ });
+ };
+
+ var toArray = function (value) {
+ if (!Array.isArray(value)) {
+ return [value];
+ }
+
+ return value;
+ };
+
+ cf.Graph = function (graph, nodes) {
+ if (!(this instanceof cf.Graph)) {
+ return new cf.Graph(graph, nodes);
+ }
+
+ var self = this;
+
+ var match = function (subject, predicate, object, property) {
+ var matches = [];
+
+ graph.forEach(function (triple) {
+ if (subject !== null && !inArray(triple.subject, subject)) {
+ return;
+ }
+
+ if (predicate !== null && !inArray(triple.predicate, predicate)) {
+ return;
+ }
+
+ if (object !== null && !inArray(triple.object, object)) {
+ return;
+ }
+
+ matches.push(triple[property]);
+ });
+
+ return matches;
+ };
+
+ this.node = function (value) {
+ return new cf.Graph(graph, node(toArray(value)));
+ };
+
+ this.in = function (predicate) {
+ return new cf.Graph(graph, match(null, node(toArray(predicate)), nodes, 'subject'));
+ };
+
+ this.out = function (predicate) {
+ return new cf.Graph(graph, match(nodes, node(toArray(predicate)), null, 'object'));
+ };
+
+ this.nodes = function () {
+ return nodes;
+ };
+
+ this.literal = function () {
+ if (nodes == null) {
+ return null;
+ }
+
+ return nodes
+ .map(function (node) {
+ return node.toString();
+ });
+ };
+
+ this.removeIn = function (predicate) {
+ this.nodes().forEach(function (o) {
+ if (predicate != null) {
+ node(toArray(predicate)).forEach(function (p) {
+ graph.removeMatches(null, p, o);
+ });
+ } else {
+ graph.removeMatches(null, null, o);
+ }
+ });
+
+ return new cf.Graph(graph, nodes);
+ };
+
+ this.removeOut = function (predicate) {
+ this.nodes().forEach(function (s) {
+ if (predicate != null) {
+ node(toArray(predicate)).forEach(function (p) {
+ graph.removeMatches(s, p, null);
+ });
+ } else {
+ graph.removeMatches(s, null, null);
+ }
+ });
+
+ return new cf.Graph(graph, nodes);
+ };
+ };
+
+ rdf.cf = cf;
+};
+
+
+module.exports = init;
+
+},{}],2:[function(require,module,exports){
+'use strict';
+
+
+var InMemoryStore = function (rdf) {
+ var graphs = {};
+
+ this.graph = function (iri, callback) {
+ var graph = null;
+
+ if (iri === undefined) {
+ graph = rdf.createGraph();
+
+ this.forEach(function (toAdd) {
+ graph.addAll(toAdd);
+ });
+ } else if (iri in graphs) {
+ graph = graphs[iri];
+ }
+
+ callback(graph);
+ };
+
+ this.match = function (iri, subject, predicate, object, callback, limit) {
+ this.graph(iri, function (graph) {
+ if (!graph) {
+ callback(null);
+ } else {
+ callback(graph.match(subject, predicate, object, limit));
+ }
+ });
+ };
+
+ this.add = function (iri, graph, callback) {
+ graphs[iri] = rdf.createGraph();
+ graphs[iri].addAll(graph);
+
+ callback(graph);
+ };
+
+ this.merge = function (iri, graph, callback) {
+ if (iri in graphs) {
+ graphs[iri].addAll(graph);
+ } else {
+ graphs[iri] = graph;
+ }
+
+ callback(graph);
+ };
+
+ this.remove = function (iri, graph, callback) {
+ if (iri in graphs) {
+ graphs[iri] = rdf.Graph.difference(graphs[iri], graph);
+ }
+
+ callback(true);
+ };
+
+ this.removeMatches = function (iri, subject, predicate, object, callback) {
+ if (iri in graphs) {
+ graphs[iri].removeMatches(subject, predicate, object);
+ }
+
+ callback(true);
+ };
+
+ this.delete = function (iri, callback) {
+ if (iri in graphs) {
+ delete graphs[iri];
+ }
+
+ callback(true);
+ };
+
+ this.forEach = function (callback) {
+ Object.keys(graphs).forEach(function (iri) {
+ callback(graphs[iri], iri);
+ });
+ };
+};
+
+
+module.exports = function (rdf) {
+ rdf.InMemoryStore = InMemoryStore.bind(null, rdf);
+
+ // use as default store
+ rdf.createStore = function () {
+ return new rdf.InMemoryStore();
+ };
+};
+
+},{}],3:[function(require,module,exports){
+'use strict';
+
+
+var
+ jsonld = require('jsonld'),
+ RDFa = require('jsonld/js/rdfa');
+
+
+var JsonLdParser = function (rdf) {
+ var jsonldExpandFlat = function (data, base, callback) {
+ jsonld.expand(data, {'base': base}, function (error, expanded) {
+ if (error) {
+ return callback(null, error.message);
+ }
+
+ jsonld.flatten(expanded, {}, function (error, flattened) {
+ if (error) {
+ return callback(null, error.message);
+ }
+
+ if (!('@graph' in flattened)) {
+ return callback(null);
+ }
+
+ callback(flattened['@graph']);
+ });
+ });
+ };
+
+ var toArray = function (object) {
+ object = object || [];
+
+ if (Array.isArray(object)) {
+ return object;
+ }
+
+ return [object];
+ };
+
+ this.process = function (data, callback, base, filter, done) {
+ if (typeof data === 'string') {
+ data = JSON.parse(data);
+ }
+
+ base = base || '';
+ filter = filter || function () { return true; };
+ done = done || function () {};
+
+ var getLiteral = function (jNode) {
+ var
+ type = null,
+ lang = null;
+
+ if ('@type' in jNode) {
+ type = getNode(jNode['@type']);
+ }
+
+ if ('@language' in jNode) {
+ lang = jNode['@language'];
+ }
+
+ return rdf.createLiteral(jNode['@value'], lang, type);
+ };
+
+ var nodeCache = {};
+
+ var getNode = function (jNode) {
+ // is there already a node?
+ if (jNode in nodeCache) {
+ return nodeCache[jNode];
+ }
+
+ // is it a blank node?
+ if (!jNode) {
+ return rdf.createBlankNode();
+ }
+
+ if (jNode.indexOf('_:') === 0) {
+ return (nodeCache[jNode] = rdf.createBlankNode());
+ }
+
+ // if not it's a named node
+ return (nodeCache[jNode] = rdf.createNamedNode(jNode));
+ };
+
+ var pushTriple = function (subject, predicate, object) {
+ var triple = rdf.createTriple(subject, predicate, object);
+
+ if (filter(triple)) {
+ callback(triple);
+ }
+ };
+
+ var processSubject = function (jSubject) {
+ var
+ subject = jSubject['@id'],
+ types = toArray(jSubject['@type']);
+
+ // add type triples
+ types.forEach(function (type) {
+ pushTriple(
+ getNode(subject),
+ getNode(rdf.ns.type),
+ getNode(type));
+ });
+
+ // other triples
+ for (var predicate in jSubject) {
+ // ignore JSON-LD properties
+ if (predicate.indexOf('@') === 0) {
+ continue;
+ }
+
+ processPredicate(subject, predicate, toArray(jSubject[predicate]));
+ }
+ };
+
+ var processPredicate = function (subject, predicate, jObjects) {
+ jObjects.forEach(function (jObject) {
+ pushTriple(
+ getNode(subject),
+ getNode(predicate),
+ processObject(jObject));
+ });
+ };
+
+ var processObject = function (jObject) {
+ // is it a simple literal?
+ if (typeof jObject === 'string') {
+ return rdf.createLiteral(jObject);
+ }
+
+ // or blank node / named node
+ if ('@id' in jObject) {
+ return getNode(jObject['@id']);
+ }
+
+ if ('@list' in jObject) {
+ return processList(jObject['@list']);
+ }
+
+ // or complex literal
+ return getLiteral(jObject);
+ };
+
+ var processList = function (jList) {
+ var
+ entry = getNode(),
+ subject = entry,
+ rest;
+
+ jList.forEach(function (jItem, index) {
+ if (index !== jList.length-1) {
+ rest = getNode();
+ } else {
+ rest = getNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#nil');
+ }
+
+ pushTriple(
+ subject,
+ getNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#first'),
+ getNode(jItem['@id']));
+
+ pushTriple(
+ subject,
+ getNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#rest'),
+ rest);
+
+ subject = rest;
+ });
+
+ return entry;
+ };
+
+ jsonldExpandFlat(data, base, function (jGraph, error) {
+ if (error) {
+ return done(false, error);
+ }
+
+ if (!jGraph) {
+ return done(true);
+ }
+
+ jGraph.forEach(function (jSubject) {
+ processSubject(jSubject);
+ });
+
+ done(true);
+ });
+
+ return true;
+ };
+
+ this.parse = function (data, callback, base, filter, graph) {
+ graph = graph || rdf.createGraph();
+
+ return this.process(
+ data,
+ function (triple) { graph.add(triple); },
+ base,
+ filter,
+ function (success, error) { callback(success ? graph : null, error); });
+ };
+};
+
+
+var RdfaParser = function (rdf) {
+ var jsonLdParser = new JsonLdParser(rdf);
+
+ this.parse = function (rdfaData, callback, base, filter, graph) {
+ if (typeof rdfaData === 'string') {
+ try {
+ rdfaData = rdf.parseHtml(rdfaData);
+ } catch (error) {
+ callback(null, error);
+
+ return false;
+ }
+ }
+
+ graph = graph || rdf.createGraph();
+
+ rdfaData.location = { href: base };
+ RDFa.attach(rdfaData);
+
+ jsonld.fromRDF(rdfaData.data, {format: 'rdfa-api'}, function (error, jsonLdData) {
+ if (error) {
+ callback(null, error);
+ } else {
+ jsonLdParser.process(
+ jsonLdData,
+ function (triple) {
+ graph.add(triple);
+ },
+ base,
+ filter,
+ function (success, error) {
+ callback(success ? graph : null, error);
+ });
+ }
+ });
+
+ return true;
+ };
+};
+
+
+module.exports = function (rdf) {
+ rdf.JsonLdParser = JsonLdParser.bind(null, rdf);
+
+ var jsonLdParser = new JsonLdParser(rdf);
+ rdf.parseJsonLd = jsonLdParser.parse.bind(jsonLdParser);
+
+ rdf.RdfaParser = RdfaParser.bind(null, rdf);
+
+ var rdfaParser = new RdfaParser(rdf);
+ rdf.parseRdfa = rdfaParser.parse.bind(rdfaParser);
+};
+
+},{"jsonld":44,"jsonld/js/rdfa":45}],4:[function(require,module,exports){
+'use strict';
+
+
+var
+ jsonld = require('jsonld');
+
+
+var JsonLdSerializer = function (rdf) {
+ var rdfStringNode = rdf.createNamedNode('http://www.w3.org/2001/XMLSchema#string');
+
+ this.serialize = function (graph, callback) {
+ callback = callback || function () {};
+
+ var jsonGraph = [];
+ var subjects = {};
+
+ var subjectIndex = function (s) {
+ var sValue = s.valueOf();
+
+ if (typeof subjects[sValue] === 'undefined') {
+ if (s.interfaceName == 'BlankNode') {
+ jsonGraph.push({ '@id': '_:' + sValue });
+ } else {
+ jsonGraph.push({ '@id': sValue });
+ }
+
+ subjects[sValue] = jsonGraph.length - 1;
+ }
+
+ return subjects[sValue];
+ };
+
+ var objectValue = function (o) {
+ if (o.interfaceName == 'NamedNode') {
+ return { '@id': o.valueOf() };
+ } else if (o.interfaceName == 'BlankNode') {
+ return { '@id': '_:' + o.valueOf()};
+ } else {
+ if (o.language) {
+ return { '@language': o.language, '@value': o.valueOf() };
+ } else if ('datatype' in o && o.datatype && !rdfStringNode.equals(o.datatype)) {
+ return { '@type': o.datatype.valueOf(), '@value': o.valueOf() };
+ } else {
+ return o.valueOf();
+ }
+ }
+ };
+
+ graph.forEach(function (t) {
+ var s = subjectIndex(t.subject);
+ var p = t.predicate.valueOf();
+
+ if (p == 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type') {
+ if (typeof jsonGraph[s]['@type'] === 'undefined') {
+ jsonGraph[s]['@type'] = [];
+ }
+
+ jsonGraph[s]['@type'].push(t.object.valueOf());
+ } else {
+ if (typeof jsonGraph[s][p] === 'undefined') {
+ jsonGraph[s][p] = objectValue(t.object);
+ } else {
+ if (!Array.isArray(jsonGraph[s][p])) {
+ jsonGraph[s][p] = [jsonGraph[s][p]];
+ }
+
+ jsonGraph[s][p].push(objectValue(t.object));
+ }
+ }
+ });
+
+ callback(jsonGraph);
+
+ return jsonGraph;
+ };
+};
+
+
+module.exports = function (rdf) {
+ rdf.JsonLdSerializer = JsonLdSerializer.bind(null, rdf);
+
+ var serializer = new JsonLdSerializer(rdf);
+ rdf.serializeJsonLd = (serializer).serialize.bind(serializer);
+};
+
+},{"jsonld":44}],5:[function(require,module,exports){
+'use strict';
+
+
+var LdpStore = function (rdf, options) {
+ var self = this;
+
+ options = options || {};
+
+ self.parsers = options.parsers || LdpStore.defaultParsers(rdf);
+ self.serializers = options.serializers || LdpStore.defaultSerializers(rdf);
+ self.defaultParser = options.defaultParser || 'text/turtle';
+ self.defaultSerializer = options.defaultSerializer || 'text/turtle';
+ self.defaultPatchSerializer = options.defaultPatchSerializer || options.defaultSerializer || 'text/turtle';
+ self.request = options.request || rdf.defaultRequest;
+
+ var buildAccept = function() {
+ var accept = null;
+
+ for (var mimeType in self.parsers) {
+ if (!accept) {
+ accept = mimeType;
+ } else {
+ accept += ', ' + mimeType;
+ }
+ }
+
+ return accept;
+ };
+
+ var httpSuccess = function (statusCode) {
+ return (statusCode >= 200 && statusCode < 300);
+ };
+
+ self.graph = function (iri, callback, options) {
+ options = options || {};
+
+ self.request('GET', iri, {'Accept': buildAccept()}, null,
+ function (statusCode, headers, content, error) {
+ // error during request
+ if (error) {
+ return callback(null, 'request error: ' + error);
+ }
+
+ // http status code != success
+ if (!httpSuccess(statusCode)) {
+ // in case of GET allow statusCode of 0 for browser local load
+ if (statusCode !== 0) {
+ return callback(null, 'status code error: ' + statusCode);
+ }
+ }
+
+ // use default parser...
+ var contentType = self.defaultParser;
+
+ // ...if content-type is not given or unknown
+ if ('content-type' in headers && headers['content-type'] in self.parsers) {
+ contentType = headers['content-type'];
+ }
+
+ // and override if set in options
+ if ('forceContentType' in options && options.forceContentType in self.parsers) {
+ contentType = options.forceContentType;
+ }
+
+ self.parsers[contentType](content, function (graph, error) {
+ // parser error
+ if (error) {
+ return callback(null, 'parser error: ' + error);
+ }
+
+ // copy etag header to Graph object
+ if ('useEtag' in options && options.useEtag && 'etag' in headers) {
+ graph.etag = headers.etag;
+ }
+
+ callback(graph);
+ }, iri);
+ }
+ );
+ };
+
+ self.match = function (iri, subject, predicate, object, callback, limit) {
+ self.graph(iri, function (graph, error) {
+ // forward error
+ if (error) {
+ return callback(null, error);
+ }
+
+ callback(graph.match(subject, predicate, object, limit));
+ });
+ };
+
+ self.add = function (iri, graph, callback, options) {
+ var
+ method = 'PUT',
+ contentType = self.defaultSerializer,
+ headers = {};
+
+ options = options || {};
+
+ headers['Content-Type'] = contentType;
+
+ if ('method' in options) {
+ method = options.method;
+ }
+
+ if ('etag' in options) {
+ headers['If-Match'] = options.etag;
+ }
+
+ if ('useEtag' in options && options.useEtag && 'etag' in graph) {
+ headers['If-Match'] = graph.etag;
+ }
+
+ self.serializers[contentType](graph, function (data, error) {
+ // serializer error
+ if (error) {
+ return callback(null, error);
+ }
+
+ self.request(method, iri, headers, data, function (statusCode, headers, content, error) {
+ // error during request
+ if (error) {
+ return callback(null, error);
+ }
+
+ // http status code != success
+ if (!httpSuccess(statusCode)) {
+ return callback(null, 'status code error: ' + statusCode);
+ }
+
+ callback(graph);
+ });
+ });
+ };
+
+ self.merge = function (iri, graph, callback, options) {
+ var
+ contentType = self.defaultPatchSerializer,
+ headers = {};
+
+ options = options || {};
+
+ headers['Content-Type'] = contentType;
+
+ if ('etag' in options) {
+ headers['If-Match'] = options.etag;
+ }
+
+ if ('useEtag' in options && options.useEtag && 'etag' in graph) {
+ headers['If-Match'] = graph.etag;
+ }
+
+ self.serializers[contentType](graph, function (data, error) {
+ // serializer error
+ if (error) {
+ return callback(null, error);
+ }
+
+ self.request('PATCH', iri, headers, data, function (statusCode, headers, content, error) {
+ // error during request
+ if (error) {
+ return callback(null, error);
+ }
+
+ // http status code != success
+ if (!httpSuccess(statusCode)) {
+ return callback(null, 'status code error: ' + statusCode);
+ }
+
+ callback(graph);
+ }
+ );
+ });
+ };
+
+ self.remove = function (iri, graph, callback) {
+ //TODO: implement me
+ };
+
+ self.removeMatches = function (iri, subject, predicate, object, callback) {
+ //TODO: implement me
+ };
+
+ self.delete = function (iri, callback) {
+ self.request('DELETE', iri, {}, null,
+ function (statusCode, headers, content, error) {
+ // error during request
+ if (error) {
+ return callback(false, 'request error: ' + error);
+ }
+
+ // http status code != success
+ if (!httpSuccess(statusCode)) {
+ return callback(false, 'status code error: ' + statusCode);
+ }
+
+ callback(true);
+ }
+ );
+ };
+};
+
+
+LdpStore.serializeSparqlUpdate = function (rdf, graph, callback) {
+ rdf.serializeNTriples(graph, function (nTriples, error) {
+ if (error) {
+ return callback(null, error);
+ }
+
+ callback('INSERT DATA { ' + nTriples + ' }');
+ });
+};
+
+
+LdpStore.defaultParsers = function(rdf) {
+ return {
+ 'application/ld+json': rdf.parseJsonLd,
+ 'application/n-triples': rdf.parseTurtle,
+ 'text/turtle': rdf.parseTurtle
+ };
+};
+
+
+LdpStore.defaultSerializers = function (rdf) {
+ return {
+ 'application/ld+json': rdf.serializeJsonLd,
+ 'application/n-triples': rdf.serializeNTriples,
+ 'application/sparql-update': LdpStore.serializeSparqlUpdate.bind(null, rdf),
+ 'text/turtle': rdf.serializeNTriples
+ };
+};
+
+
+module.exports = function (rdf) {
+ rdf.LdpStore = LdpStore.bind(null, rdf);
+};
+
+},{}],6:[function(require,module,exports){
+/* global rdf */
+'use strict';
+
+
+var
+ URIResolver = require('./uri-resolver');
+
+
+var MicrodataProcessor = function () {
+ this.blankCounter = 0;
+
+ this.vocabularies = [{
+ namespaceURI: 'http://schema.org/',
+ isMember: function (uri) {
+ return uri.indexOf(this.namespaceURI) === 0;
+ },
+ getProperty: function (name) {
+ return this.namespaceURI + name;
+ }
+ }];
+};
+
+MicrodataProcessor.prototype = new URIResolver();
+MicrodataProcessor.prototype.constructor = MicrodataProcessor;
+
+MicrodataProcessor.typeNode = rdf.createNamedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type');
+MicrodataProcessor.integerNode = rdf.createNamedNode('http://www.w3.org/2001/XMLSchema#integer');
+MicrodataProcessor.doubleNode = rdf.createNamedNode('http://www.w3.org/2001/XMLSchema#double');
+MicrodataProcessor.timeNode = rdf.createNamedNode('http://www.w3.org/2001/XMLSchema#time');
+MicrodataProcessor.dateTimeNode = rdf.createNamedNode('http://www.w3.org/2001/XMLSchema#dateTime');
+MicrodataProcessor.durationNode = rdf.createNamedNode('http://www.w3.org/2001/XMLSchema#duration');
+
+MicrodataProcessor.absoluteURIRE = /[\w\_\-]+:\S+/;
+
+MicrodataProcessor.prototype.resolve = function (uri) {
+ return uri;
+};
+
+MicrodataProcessor.trim = function (str) {
+ str = str || '';
+
+ return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
+};
+
+MicrodataProcessor.tokenize = function (str) {
+ return MicrodataProcessor
+ .trim(str)
+ .split(/\s+/)
+ .reduce(function (tokens, token) {
+ if (token) {
+ tokens.push(token);
+ }
+
+ return tokens;
+ }, []);
+};
+
+MicrodataProcessor.prototype.getVocabulary = function (uri) {
+ for (var i=0; i<this.vocabularies.length; i++) {
+ if (this.vocabularies[i].isMember(uri)) {
+ return this.vocabularies[i];
+ }
+ }
+
+ var makeVocab = function(ns) {
+ return {
+ namespaceURI: ns,
+ getProperty: function(name) {
+ return this.namespaceURI + name;
+ }
+ };
+ };
+
+ var hash = uri.indexOf("#");
+
+ if (hash >= 0) {
+ return makeVocab(uri.substring(0,hash+1));
+ }
+
+ var lastSlash = uri.lastIndexOf('/');
+
+ if (lastSlash >= 0) {
+ return makeVocab(uri.substring(0,lastSlash+1));
+ }
+
+ return makeVocab(uri);
+};
+
+MicrodataProcessor.prototype.getProperty = function (value, vocabulary) {
+ if (MicrodataProcessor.absoluteURIRE.exec(value)) {
+ return value;
+ }
+
+ return vocabulary ? vocabulary.getProperty(value) : base.resolve('#' + value);
+};
+
+MicrodataProcessor.valueMappings = {
+ link: function(node,base) {
+ return rdf.createNamedNode(base.resolve(node.getAttribute('href')));
+ },
+ media: function (node, base) {
+ return rdf.createNamedNode(base.resolve(node.getAttribute('src')));
+ },
+ meta: function (node) {
+ var
+ value = node.getAttribute('content'),
+ lang = node.getAttribute('lang');
+
+ return rdf.createLiteral(value, lang ? lang : null);
+ },
+ number: function (node) {
+ var value = node.getAttribute('value');
+
+ if (value === parseInt(value).toString()) {
+ return rdf.createLiteral(value, null, MicrodataProcessor.integerNode);
+ } else if (value === parseFloat(value).toString()) {
+ return rdf.createLiteral(value, null, MicrodataProcessor.doubleNode);
+ } else {
+ return rdf.createLiteral(value);
+ }
+ },
+ object: function (node, base) {
+ return rdf.createNamedNode(base.resolve(node.getAttribute('data')));
+ },
+ time: function(node) {
+ var
+ value = node.getAttribute('datetime'),
+ lang = node.getAttribute('lang');
+
+ //TODO: add http://www.w3.org/2001/XMLSchema#gYearMonth.
+ //TODO: add http://www.w3.org/2001/XMLSchema#gYear.
+ //TODO: use RegExp
+ if (value.length === 9) {
+ return rdf.createLiteral(value, null, MicrodataProcessor.timeNode);
+ } else if (value.length === 20) {
+ return rdf.createLiteral(value, null, MicrodataProcessor.dateTimeNode);
+ } else if (value.substr(0, 1) === 'P') {
+ return rdf.createLiteral(value, null, MicrodataProcessor.durationNode);
+ } else {
+ return rdf.createLiteral(value, lang ? lang : null);
+ }
+ }
+};
+
+MicrodataProcessor.valueMappings.a = MicrodataProcessor.valueMappings.link;
+MicrodataProcessor.valueMappings.area = MicrodataProcessor.valueMappings.a;
+MicrodataProcessor.valueMappings.audio = MicrodataProcessor.valueMappings.media;
+MicrodataProcessor.valueMappings.data = MicrodataProcessor.valueMappings.number;
+MicrodataProcessor.valueMappings.embed = MicrodataProcessor.valueMappings.media;
+MicrodataProcessor.valueMappings.iframe = MicrodataProcessor.valueMappings.media;
+MicrodataProcessor.valueMappings.img = MicrodataProcessor.valueMappings.media;
+MicrodataProcessor.valueMappings.meter = MicrodataProcessor.valueMappings.number;
+MicrodataProcessor.valueMappings.source = MicrodataProcessor.valueMappings.media;
+MicrodataProcessor.valueMappings.track = MicrodataProcessor.valueMappings.media;
+MicrodataProcessor.valueMappings.video = MicrodataProcessor.valueMappings.media;
+
+MicrodataProcessor.prototype.getValue = function(node, base) {
+ var converter = MicrodataProcessor.valueMappings[node.localName];
+
+ if (converter) {
+ return converter(node, base);
+ }
+
+ return rdf.createLiteral(node.textContent);
+};
+
+MicrodataProcessor.prototype.process = function (node, callback, base) {
+ var
+ self = this;
+
+ if (node.nodeType === node.DOCUMENT_NODE) {
+ node = node.documentElement;
+ }
+
+ base = self.parseURI(base);
+
+ var createContext = function (memory, subject, type, vocabulary) {
+ return {
+ memory: memory ? memory : {},
+ subject: subject,
+ type: type,
+ vocabulary: vocabulary
+ };
+ };
+
+ var processChildren = function (current, type) {
+ var
+ context,
+ itemProp,
+ itemScope,
+ predicate,
+ subject,
+ value;
+
+ for (var child = current.item.firstChild; child; child = child.nextSibling) {
+ if (child.nodeType !== child.ELEMENT_NODE) {
+ continue;
+ }
+
+ itemProp = child.getAttribute('itemprop');
+ itemScope = child.hasAttribute('itemscope');
+
+ // spec 6.3.9.1.1
+ context = createContext(current.context.memory, current.context.subject, type, current.context.vocabulary);
+
+ subject = generateTriple({item: child, context: context});
+
+ if (itemProp) {
+ // spec 6.3.9.1
+ MicrodataProcessor.tokenize(itemProp).forEach(function (token) {
+ // spec 6.3.9.1.2
+ //TODO: Let predicate be the result of generate predicate URI using context and name
+ if (MicrodataProcessor.absoluteURIRE.test(token)) {
+ predicate = rdf.createNamedNode(token);
+ } else if (context.vocabulary) {
+ predicate = rdf.createNamedNode(context.vocabulary + token);
+ } else {
+ predicate = rdf.createNamedNode(base.resolve('#' + token));
+ }
+
+ // spec 6.3.9.1.3
+ //TODO: Let value be the property value of element
+ value = self.getValue(child, base);
+
+ // spec 6.3.9.1.4
+ //TODO: If value is an item, then generate the triples for value using context. Replace value by the subject returned from those steps
+ if (itemScope) {
+ value = subject;
+ }
+
+ // spec 6.3.9.1.5
+
+ callback(rdf.createTriple(
+ current.context.subject,
+ predicate,
+ value
+ ));
+
+ // spec 6.3.9.1.6
+ //TODO: If an entry exists in the registry for name in the vocabulary associated with vocab having the key subPropertyOf or equivalentProperty, for each such value equiv, generate the following triple:
+ });
+ }
+ }
+ };
+
+ var processSubject = function (current) {
+ var
+ itemType = current.item.getAttribute('itemtype'),
+ type,
+ vocab;
+
+ // spec 6.3.3
+ MicrodataProcessor.tokenize(itemType).forEach(function (token) {
+ if (!MicrodataProcessor.absoluteURIRE.test(token)) {
+ return;
+ }
+
+ // spec 6.3.4
+ if (!type) {
+ type = token;
+ }
+
+ callback(rdf.createTriple(
+ current.context.subject,
+ MicrodataProcessor.typeNode,
+ rdf.createNamedNode(base.resolve(token))));
+ });
+
+ // spec 6.3.5
+ if (!type) {
+ type = current.context.type;
+ }
+
+ // spec 6.3.6
+ //TODO: If the registry contains a URI prefix that is a character for character match of type up to the length of the URI prefix, set vocab as that URI prefix
+ // spec 6.3.7
+ //TODO: Otherwise, if type is not empty, construct vocab by removing everything following the last SOLIDUS U+002F ("/") or NUMBER SIGN U+0023 ("#") from the path component of type
+ if (type) {
+ vocab = self.getVocabulary(type); //TODO: return only uri string
+ vocab = vocab ? vocab.namespaceURI : null;
+ }
+
+ // spec 6.3.8
+ //TODO: Update evaluation context setting current vocabulary to vocab
+ if (vocab) {
+ current.context.vocabulary = vocab;
+ }
+
+ // spec 6.3.9
+ processChildren(current, type);
+ };
+
+ var generateTriple = function (current) {
+ var
+ id = current.item.getAttribute('id'),
+ itemId = current.item.getAttribute('itemid'),
+ itemRef = current.item.getAttribute('itemref'),
+ itemScope = current.item.hasAttribute('itemscope');
+
+ // spec 6.3.1
+ if (id in current.context.memory) {
+ current.context.memory[id].forEach(function (context) {
+ processSubject({item: current.item, context: context});
+ });
+ } else {
+ if (itemScope) {
+ if (itemId) {
+ current.context.subject = rdf.createNamedNode(base.resolve(itemId));
+ } else {
+ current.context.subject = rdf.createBlankNode();
+ }
+
+ // spec 6.3.2
+ //TODO: Add a mapping from item to subject in memory
+ MicrodataProcessor.tokenize(itemRef).forEach(function (token) {
+ if (!(token in current.context.memory)) {
+ current.context.memory[token] = [];
+ }
+
+ current.context.memory[token].push(current.context);
+ });
+ }
+
+ processSubject(current);
+ }
+
+ return current.context.subject;
+ };
+
+ generateTriple({item: node, context: createContext(null, null, null, null)});
+};
+
+var MicrodataParser = function (rdf) {
+ var processor = new MicrodataProcessor();
+
+ this.process = function (data, callback, base, filter, done) {
+ base = base || '';
+ filter = filter || function () { return true; };
+ done = done || function () {};
+
+ processor.process(rdf.parseHtml(data, base), callback, base);
+
+ done(true);
+
+ return true;
+ };
+
+ this.parse = function (data, callback, base, filter, graph) {
+ graph = graph || rdf.createGraph();
+
+ return this.process(
+ data,
+ function (triple) { graph.add(triple); },
+ base,
+ filter,
+ function (success) { callback(success ? graph : null); });
+ };
+};
+
+
+module.exports = function (rdf) {
+ rdf.MicrodataParser = MicrodataParser.bind(null, rdf);
+
+ var parser = new MicrodataParser(rdf);
+ rdf.parseMicrodata = parser.parse.bind(parser);
+};
+
+},{"./uri-resolver":14}],7:[function(require,module,exports){
+/* global rdf:true */
+'use strict';
+
+
+var NTriplesSerializer = function (rdf) {
+ this.serialize = function (graph, callback) {
+ callback = callback || function () {};
+
+ var nTriples = rdf.Graph.toString(graph);
+
+ callback(nTriples);
+
+ return nTriples;
+ };
+};
+
+
+module.exports = function (rdf) {
+ rdf.NTriplesSerializer = NTriplesSerializer.bind(null, rdf);
+
+ var serializer = new NTriplesSerializer(rdf);
+ rdf.serializeNTriples = serializer.serialize.bind(serializer);
+};
+
+},{}],8:[function(require,module,exports){
+/* global rdf:true, Promise:false */
+'use strict';
+
+
+var funcTemplate = function (func, PromiseClass) {
+ return function () {
+ var args = arguments;
+
+ return new PromiseClass(function (resolve, reject) {
+ var callback = function (result, error) {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(result);
+ }
+ };
+
+ func(args, callback);
+ });
+ };
+};
+
+
+var ParserPromiseWrapper = function (p, parser) {
+ this.process = funcTemplate(function (args, callback) { parser.process(args[0], args[1], args[2], args[3], callback); }, p);
+ this.parse = funcTemplate(function (args, callback) { parser.parse(args[0], callback, args[1], args[2], args[3]); }, p);
+ this.parser = function () { return parser; };
+};
+
+
+var SerializerPromiseWrapper = function (p, serializer) {
+ this.serialize = funcTemplate(function (args, callback) { serializer.serialize(args[0], callback); }, p);
+ this.serializer = function () { return serializer; };
+};
+
+
+var StorePromiseWrapper = function (p, store) {
+ this.graph = funcTemplate(function (args, callback) { store.graph(args[0], callback); }, p);
+ this.match = funcTemplate(function (args, callback) { store.match(args[0], args[1], args[2], args[3], callback, args[5]); }, p);
+ this.add = funcTemplate(function (args, callback) { store.add(args[0], args[1], callback); }, p);
+ this.merge = funcTemplate(function (args, callback) { store.merge(args[0], args[1], callback); }, p);
+ this.remove = funcTemplate(function (args, callback) { store.remove(args[0], args[1], callback); }, p);
+ this.removeMatches = funcTemplate(function (args, callback) { store.removeMatches(args[0], args[1], args[2], args[3], callback); }, p);
+ this.delete = funcTemplate(function (args, callback) { store.delete(args[0], callback); }, p);
+ this.store = function () { return store; };
+};
+
+
+module.exports = function (rdf) {
+ rdf.promise = {};
+ rdf.promise.Parser = ParserPromiseWrapper.bind(null, rdf.Promise);
+ rdf.promise.Serializer = SerializerPromiseWrapper.bind(null, rdf.Promise);
+ rdf.promise.Store = StorePromiseWrapper.bind(null, rdf.Promise);
+};
+
+},{}],9:[function(require,module,exports){
+/* global rdf:true */
+'use strict';
+
+
+var RdfstoreStore = function (store) {
+ var
+ self = this,
+ rdf = store.rdf;
+
+ self.graph = function (iri, callback) {
+ store.graph(iri, function (success, graph) {
+ if (success) {
+ callback(graph);
+ } else {
+ callback(null);
+ }
+ });
+ };
+
+ self.match = function (iri, subject, predicate, object, callback, limit) {
+ self.graph(iri, function (graph) {
+ if (!graph) {
+ callback(null);
+ } else {
+ callback(graph.match(subject, predicate, object, limit));
+ }
+ });
+ };
+
+ self.add = function (iri, graph, callback) {
+ store.clear(iri, function () {
+ store.insert(graph, iri, function (success) {
+ if (success) {
+ callback(graph);
+ } else {
+ callback(null, 'couldn\'n insert graph');
+ }
+ });
+ });
+ };
+
+ self.merge = function (iri, graph, callback) {
+ store.insert(graph, iri, function (success) {
+ if (success) {
+ callback(graph);
+ } else {
+ callback(null, 'couldn\'n insert graph');
+ }
+ });
+ };
+
+ self.remove = function (iri, graph, callback) {
+ self.graph(iri, function (oldGraph) {
+ var newGraph = rdf.Graph.difference(oldGraph, graph);
+
+ self.add(iri, newGraph, function (addedGraph) {
+ callback(!!addedGraph);
+ });
+ });
+ };
+
+ self.removeMatches = function (iri, subject, predicate, object, callback) {
+ self.graph(iri, function (oldGraph) {
+ var newGraph = oldGraph.removeMatches(subject, predicate, object);
+
+ self.add(iri, newGraph, function (addedGraph) {
+ callback(!!addedGraph);
+ });
+ });
+ };
+
+ self.delete = function (iri, callback) {
+ store.clear(iri, function (success) {
+ if (success) {
+ callback(true);
+ } else {
+ callback(null, 'couldn\'n delete graph');
+ }
+ });
+ };
+};
+
+
+module.exports = function (rdf) {
+ rdf.RdfstoreStore = RdfstoreStore;
+};
+
+},{}],10:[function(require,module,exports){
+/**
+ * @fileoverview
+ * RDF/XML PARSER
+ *
+ * Version 0.1
+ * Parser believed to be in full positive RDF/XML parsing compliance
+ * with the possible exception of handling deprecated RDF attributes
+ * appropriately. Parser is believed to comply fully with other W3C
+ * and industry standards where appropriate (DOM, ECMAScript, &c.)
+ *
+ * Author: David Sheets <ds...@mit.edu>
+ *
+ * W3C� SOFTWARE NOTICE AND LICENSE
+ * http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
+ * This work (and included software, documentation such as READMEs, or
+ * other related items) is being provided by the copyright holders under
+ * the following license. By obtaining, using and/or copying this work,
+ * you (the licensee) agree that you have read, understood, and will
+ * comply with the following terms and conditions.
+ *
+ * Permission to copy, modify, and distribute this software and its
+ * documentation, with or without modification, for any purpose and
+ * without fee or royalty is hereby granted, provided that you include
+ * the following on ALL copies of the software and documentation or
+ * portions thereof, including modifications:
+ *
+ * 1. The full text of this NOTICE in a location viewable to users of
+ * the redistributed or derivative work.
+ * 2. Any pre-existing intellectual property disclaimers, notices, or terms and
+ * conditions. If none exist, the W3C Software Short Notice should be
+ * included (hypertext is preferred, text is permitted) within the body
+ * of any redistributed or derivative code.
+ * 3. Notice of any changes or modifications to the files, including the
+ * date changes were made. (We recommend you provide URIs to the location
+ * from which the code is derived.)
+ *
+ * THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT
+ * HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED,
+ * INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS
+ * FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR
+ * DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
+ * TRADEMARKS OR OTHER RIGHTS.
+ *
+ * COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL
+ * OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR
+ * DOCUMENTATION.
+ *
+ * The name and trademarks of copyright holders may NOT be used in
+ * advertising or publicity pertaining to the software without specific,
+ * written prior permission. Title to copyright in this software and any
+ * associated documentation will at all times remain with copyright
+ * holders.
+ */
+/**
+ * @class Class defining an RDFParser resource object tied to an RDFStore
+ *
+ * @author David Sheets <ds...@mit.edu>
+ * @version 0.1
+ *
+ * @constructor
+ * @param {RDFStore} store An RDFStore object
+ */
+
+var RdfLibParser = function(store){
+ var RDFParser = {};
+
+ /** Standard namespaces that we know how to handle @final
+ * @member RDFParser
+ */
+ RDFParser.ns = {'RDF': "http://www.w3.org/1999/02/22-rdf-syntax-ns#", 'RDFS': "http://www.w3.org/2000/01/rdf-schema#"};
+
+ /** DOM Level 2 node type magic numbers @final
+ * @member RDFParser
+ */
+ RDFParser.nodeType = {'ELEMENT': 1, 'ATTRIBUTE': 2, 'TEXT': 3,
+ 'CDATA_SECTION': 4, 'ENTITY_REFERENCE': 5,
+ 'ENTITY': 6, 'PROCESSING_INSTRUCTION': 7,
+ 'COMMENT': 8, 'DOCUMENT': 9, 'DOCUMENT_TYPE': 10,
+ 'DOCUMENT_FRAGMENT': 11, 'NOTATION': 12};
+
+ /**
+ * Frame class for namespace and base URI lookups
+ * Base lookups will always resolve because the parser knows
+ * the default base.
+ *
+ * @private
+ */
+
+ this.frameFactory = function(parser, parent, element){
+ return {'NODE': 1, 'ARC': 2, 'parent': parent, 'parser': parser, 'store': parser.store, 'element': element,
+ 'lastChild': 0, 'base': null, 'lang': null, 'node': null, 'nodeType': null, 'listIndex': 1, 'rdfid': null, 'datatype': null, 'collection': false, /** Terminate the frame and notify the store that we're done */
+ 'terminateFrame': function(){
+ if (this.collection){
+
+ this.node.close();
+ }
+ }
+ , /** Add a symbol of a certain type to the this frame */'addSymbol': function(type, uri){
+ uri = uriJoin(uri, this.base);
+ this.node = this.store.sym(uri);
+
+ this.nodeType = type;
+ }
+ , /** Load any constructed triples into the store */'loadTriple': function(){
+ if (this.parent.parent.collection){
+ this.parent.parent.node.append(this.node);
+ }
+ else {
+ this.store.add(this.parent.parent.node, this.parent.node, this.node, this.parser.why);
+ }
+ if (this.parent.rdfid != null){
+ // reify
+ var triple = this.store.sym(uriJoin("#" + this.parent.rdfid, this.base));
+ this.store.add(triple, this.store.sym(RDFParser.ns.RDF + "type"), this.store.sym(RDFParser.ns.RDF + "Statement"), this.parser.why);
+ this.store.add(triple, this.store.sym(RDFParser.ns.RDF + "subject"), this.parent.parent.node, this.parser.why);
+ this.store.add(triple, this.store.sym(RDFParser.ns.RDF + "predicate"), this.parent.node, this.parser.why);
+
+ this.store.add(triple, this.store.sym(RDFParser.ns.RDF + "object"), this.node, this.parser.why);
+ }
+ }
+ , /** Check if it's OK to load a triple */'isTripleToLoad': function(){
+
+ return (this.parent != null && this.parent.parent != null && this.nodeType === this.NODE && this.parent.nodeType ===
+ this.ARC && this.parent.parent.nodeType === this.NODE);
+ }
+ , /** Add a symbolic node to this frame */'addNode': function(uri){
+ this.addSymbol(this.NODE, uri);
+ if (this.isTripleToLoad()){
+
+ this.loadTriple();
+ }
+ }
+ , /** Add a collection node to this frame */'addCollection': function(){
+ this.nodeType = this.NODE;
+ this.node = this.store.collection();
+ this.collection = true;
+ if (this.isTripleToLoad()){
+
+ this.loadTriple();
+ }
+ }
+ , /** Add a collection arc to this frame */'addCollectionArc': function(){
+
+ this.nodeType = this.ARC;
+ }
+ , /** Add a bnode to this frame */'addBNode': function(id){
+ if (id != null){
+ if (this.parser.bnodes[id] != null){
+ this.node = this.parser.bnodes[id];
+ }
+ else {
+ this.node = this.parser.bnodes[id] = this.store.bnode();
+ }
+ }
+ else {
+ this.node = this.store.bnode();
+ }
+ this.nodeType = this.NODE;
+ if (this.isTripleToLoad()){
+
+ this.loadTriple();
+ }
+ }
+ , /** Add an arc or property to this frame */'addArc': function(uri){
+ if (uri === RDFParser.ns.RDF + "li"){
+ uri = RDFParser.ns.RDF + "_" + this.parent.listIndex;
+ this.parent.listIndex++;
+ }
+
+ this.addSymbol(this.ARC, uri);
+ }
+ , /** Add a literal to this frame */'addLiteral': function(value){
+ if (this.parent.datatype){
+ this.node = this.store.literal(value, "", this.store.sym(this.parent.datatype));
+ }
+ else {
+ this.node = this.store.literal(value, this.lang);
+ }
+ this.nodeType = this.NODE;
+ if (this.isTripleToLoad()){
+ this.loadTriple();
+ }
+ }
+ };
+ };
+
+ //from the OpenLayers source .. needed to get around IE problems.
+ this.getAttributeNodeNS = function(node, uri, name){
+ var attributeNode = null;
+ if (node.getAttributeNodeNS){
+ attributeNode = node.getAttributeNodeNS(uri, name);
+ }
+ else {
+ var attributes = node.attributes;
+ var potentialNode, fullName;
+ for (var i = 0;i < attributes.length; ++ i){
+ potentialNode = attributes[i];
+ if (potentialNode.namespaceURI === uri){
+ fullName = (potentialNode.prefix) ? (potentialNode.prefix +":" + name): name;
+ if (fullName === potentialNode.nodeName){
+ attributeNode = potentialNode;
+ break;
+ }
+ }
+ }
+ }
+ return attributeNode;
+ };
+
+
+ /** Our triple store reference @private */
+
+ this.store = store;/** Our identified blank nodes @private */
+ this.bnodes = {};/** A context for context-aware stores @private */
+ this.why = null;/** Reification flag */
+ this.reify = false;
+
+ /**
+ * Build our initial scope frame and parse the DOM into triples
+ * @param {DOMTree} document The DOM to parse
+ * @param {String} base The base URL to use
+ * @param {Object} why The context to which this resource belongs
+ */
+
+ this.parse = function(document, base, why){
+ var children = document.childNodes;// clean up for the next run
+ this.cleanParser();// figure out the root element
+ var root;
+ if (document.nodeType === RDFParser.nodeType.DOCUMENT){
+ for (var c = 0;c < children.length;c++){
+ if (children[c].nodeType === RDFParser.nodeType.ELEMENT){
+ root = children[c];
+ break;
+ }
+ }
+ }
+ else if (document.nodeType === RDFParser.nodeType.ELEMENT){
+ root = document;
+ }
+ else {
+ throw new Error("RDFParser: can't find root in " + base +". Halting. ");
+ // return false;
+ }
+ this.why = why;// our topmost frame
+ var f = this.frameFactory(this);
+ this.base = base;
+ f.base = base;
+ f.lang = '';
+ this.parseDOM(this.buildFrame(f, root));
+ return true;
+ };
+
+ this.parseDOM = function(frame){
+ // a DOM utility function used in parsing
+ var rdfid;
+ var elementURI = function(el){
+ var result = "";
+ if (el.namespaceURI == null){
+ throw new Error("RDF/XML syntax error: No namespace for " + el.localName + " in " + this.base);
+ }
+ if (el.namespaceURI){
+ result = result + el.namespaceURI;
+ }
+ if (el.localName){
+ result = result + el.localName;
+ }
+ else if (el.nodeName){
+ if (el.nodeName.indexOf(":") >= 0)result = result + el.nodeName.split(":")[1];
+ else result = result + el.nodeName;
+ }
+ return result;
+ }.bind(this);
+ var dig = true;// if we'll dig down in the tree on the next iter
+ while (frame.parent){
+ var dom = frame.element;
+ var attrs = dom.attributes;
+ if (dom.nodeType === RDFParser.nodeType.TEXT || dom.nodeType === RDFParser.nodeType.CDATA_SECTION){
+ //we have a literal
+ if(frame.parent.nodeType == frame.NODE) {
+ //must have had attributes, store as rdf:value
+ frame.addArc(RDFParser.ns.RDF + 'value');
+ frame = this.buildFrame(frame);
+ }
+ frame.addLiteral(dom.nodeValue);
+ }
+ else if (elementURI(dom)!== RDFParser.ns.RDF + "RDF"){
+ // not root
+ if (frame.parent && frame.parent.collection){
+ // we're a collection element
+ frame.addCollectionArc();
+ frame = this.buildFrame(frame, frame.element);
+ frame.parent.element = null;
+ }
+ if ( ! frame.parent || ! frame.parent.nodeType || frame.parent.nodeType === frame.ARC){
+ // we need a node
+ var about = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "about");
+ rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "ID");
+ if (about && rdfid){
+ throw new Error("RDFParser: " + dom.nodeName + " has both rdf:id and rdf:about." +
+ " Halting. Only one of these" + " properties may be specified on a" + " node.");
+ }
+ if (!about && rdfid){
+ frame.addNode("#" + rdfid.nodeValue);
+ dom.removeAttributeNode(rdfid);
+ }
+ else if (about == null && rdfid == null){
+ var bnid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "nodeID");
+ if (bnid){
+ frame.addBNode(bnid.nodeValue);
+ dom.removeAttributeNode(bnid);
+ }
+ else {
+ frame.addBNode();
+ }
+ }
+ else {
+ frame.addNode(about.nodeValue);
+ dom.removeAttributeNode(about);
+ }
+ // Typed nodes
+ var rdftype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "type");
+ if (RDFParser.ns.RDF + "Description" !== elementURI(dom)){
+ rdftype = {'nodeValue': elementURI(dom)};
+ }
+ if (rdftype != null){
+ this.store.add(frame.node, this.store.sym(RDFParser.ns.RDF + "type"), this.store.sym(uriJoin(rdftype.nodeValue,
+ frame.base)), this.why);
+ if (rdftype.nodeName){
+ dom.removeAttributeNode(rdftype);
+ }
+ }
+ // Property Attributes
+ for (var x = attrs.length - 1;x >= 0;x--){
+ this.store.add(frame.node, this.store.sym(elementURI(attrs[x])), this.store.literal(attrs[x].nodeValue,
+ frame.lang), this.why);
+ }
+ }
+ else {
+ // we should add an arc (or implicit bnode+arc)
+ frame.addArc(elementURI(dom));// save the arc's rdf:ID if it has one
+ if (this.reify){
+ rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "ID");
+ if (rdfid){
+ frame.rdfid = rdfid.nodeValue;
+ dom.removeAttributeNode(rdfid);
+ }
+ }
+ var parsetype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "parseType");
+ var datatype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "datatype");
+ if (datatype){
+ frame.datatype = datatype.nodeValue;
+ dom.removeAttributeNode(datatype);
+ }
+ if (parsetype){
+ var nv = parsetype.nodeValue;
+ if (nv === "Literal"){
+ frame.datatype = RDFParser.ns.RDF + "XMLLiteral";// (this.buildFrame(frame)).addLiteral(dom)
+ // should work but doesn't
+ frame = this.buildFrame(frame);
+ frame.addLiteral(dom);
+ dig = false;
+ }
+ else if (nv === "Resource"){
+ frame = this.buildFrame(frame, frame.element);
+ frame.parent.element = null;
+ frame.addBNode();
+ }
+ else if (nv === "Collection"){
+ frame = this.buildFrame(frame, frame.element);
+ frame.parent.element = null;
+ frame.addCollection();
+ }
+ dom.removeAttributeNode(parsetype);
+ }
+ if (attrs.length !== 0){
+ var resource = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "resource");
+ var bnid2 = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "nodeID");
+ frame = this.buildFrame(frame);
+ if (resource){
+ frame.addNode(resource.nodeValue);
+ dom.removeAttributeNode(resource);
+ }
+ else {
+ if (bnid2){
+ frame.addBNode(bnid2.nodeValue);
+ dom.removeAttributeNode(bnid2);
+ }
+ else {
+ frame.addBNode();
+ }
+ }
+ for (var x1 = attrs.length - 1; x1 >= 0; x1--){
+ var f = this.buildFrame(frame);
+ f.addArc(elementURI(attrs[x1]));
+ if (elementURI(attrs[x1])=== RDFParser.ns.RDF + "type"){
+ (this.buildFrame(f)).addNode(attrs[x1].nodeValue);
+ }
+ else {
+ (this.buildFrame(f)).addLiteral(attrs[x1].nodeValue);
+ }
+ }
+ }
+ else if (dom.childNodes.length === 0){
+ (this.buildFrame(frame)).addLiteral("");
+ }
+ }
+ }// rdf:RDF
+ // dig dug
+ dom = frame.element;
+ while (frame.parent){
+ var pframe = frame;
+ while (dom == null){
+ frame = frame.parent;
+ dom = frame.element;
+ }
+ var candidate = dom.childNodes && dom.childNodes[frame.lastChild];
+ if (!candidate || ! dig){
+ frame.terminateFrame();
+ if ( ! (frame = frame.parent)){
+ break;
+ }// done
+ dom = frame.element;
+ dig = true;
+ }
+ else if ((candidate.nodeType !== RDFParser.nodeType.ELEMENT &&
+ candidate.nodeType !== RDFParser.nodeType.TEXT &&
+ candidate.nodeType !== RDFParser.nodeType.CDATA_SECTION) ||
+ ((candidate.nodeType === RDFParser.nodeType.TEXT ||
+ candidate.nodeType === RDFParser.nodeType.CDATA_SECTION) &&
+ dom.childNodes.length !== 1)){
+ frame.lastChild++;
+ }
+ else {
+ // not a leaf
+ frame.lastChild++;
+ frame = this.buildFrame(pframe, dom.childNodes[frame.lastChild - 1]);
+ break;
+ }
+ }
+ }// while
+ };
+
+ /**
+ * Cleans out state from a previous parse run
+ * @private
+ */
+ this.cleanParser = function(){
+ this.bnodes = {};
+ this.why = null;
+ };
+
+ /**
+ * Builds scope frame
+ * @private
+ */
+ this.buildFrame = function(parent, element){
+ var frame = this.frameFactory(this, parent, element);
+ if (parent){
+ frame.base = parent.base;
+ frame.lang = parent.lang;
+ }
+ if (!element || element.nodeType === RDFParser.nodeType.TEXT ||
+ element.nodeType === RDFParser.nodeType.CDATA_SECTION){
+ return frame;
+ }
+ var attrs = element.attributes;
+ var base = element.getAttributeNode("xml:base");
+ if (base != null){
+ frame.base = base.nodeValue;
+ element.removeAttribute("xml:base");
+ }
+ var lang = element.getAttributeNode("xml:lang");
+ if (lang != null){
+ frame.lang = lang.nodeValue;
+ element.removeAttribute("xml:lang");
+ }
+ // remove all extraneous xml and xmlns attributes
+ for (var x = attrs.length - 1;x >= 0;x--){
+ if (attrs[x].nodeName.substr(0, 3) === "xml"){
+ if (attrs[x].name.slice(0, 6) === 'xmlns:'){
+ var uri = attrs[x].nodeValue;// alert('base for namespac attr:'+this.base);
+ if (this.base) uri = uriJoin(uri, this.base);
+ this.store.setPrefixForURI(attrs[x].name.slice(6), uri);
+ }
+ // alert('rdfparser: xml atribute: '+attrs[x].name) //@@
+ element.removeAttributeNode(attrs[x]);
+ }
+ }
+ return frame;
+ };
+};
+
+
+// taken from rdflib/uri.coffee
+var uriJoin = function(given, base) {
+ var baseColon, baseHash, baseScheme, baseSingle, colon, lastSlash, path;
+ baseHash = base.indexOf('#');
+ if (baseHash > 0) {
+ base = base.slice(0, baseHash);
+ }
+ if (given.length === 0) {
+ return base;
+ }
+ if (given.indexOf('#') === 0) {
+ return base + given;
+ }
+ colon = given.indexOf(':');
+ if (colon >= 0) {
+ return given;
+ }
+ baseColon = base.indexOf(':');
+ if (base.length === 0) {
+ return given;
+ }
+ if (baseColon < 0) {
+ alert("Invalid base: " + base + " in join with given: " + given);
+ return given;
+ }
+ baseScheme = base.slice(0, +baseColon + 1 || 9e9);
+ if (given.indexOf('//') === 0) {
+ return baseScheme + given;
+ }
+ if (base.indexOf('//', baseColon) === baseColon + 1) {
+ baseSingle = base.indexOf('/', baseColon + 3);
+ if (baseSingle < 0) {
+ if (base.length - baseColon - 3 > 0) {
+ return base + '/' + given;
+ } else {
+ return baseScheme + given;
+ }
+ }
+ } else {
+ baseSingle = base.indexOf('/', baseColon + 1);
+ if (baseSingle < 0) {
+ if (base.length - baseColon - 1 > 0) {
+ return base + '/' + given;
+ } else {
+ return baseScheme + given;
+ }
+ }
+ }
+ if (given.indexOf('/') === 0) {
+ return base.slice(0, baseSingle) + given;
+ }
+ path = base.slice(baseSingle);
+ lastSlash = path.lastIndexOf('/');
+ if (lastSlash < 0) {
+ return baseScheme + given;
+ }
+ if (lastSlash >= 0 && lastSlash < path.length - 1) {
+ path = path.slice(0, +lastSlash + 1 || 9e9);
+ }
+ path += given;
+ while (path.match(/[^\/]*\/\.\.\//)) {
+ path = path.replace(/[^\/]*\/\.\.\//, '');
+ }
+ path = path.replace(/\.\//g, '');
+ path = path.replace(/\/\.$/, '/');
+ return base.slice(0, baseSingle) + path;
+};
+
+
+// RDF-Interface API
+var RdfXmlParser = function (rdf) {
+ this.process = function (toparse, callback, base, filter, done) {
+ if (typeof toparse === 'string') {
+ toparse = rdf.parseXml(toparse);
+ }
+
+ base = base || '';
+ filter = filter || function() { return true; };
+
+ // convert an array of DOM nodes to a XML string
+ var domNodesToString = function (nodes) {
+ var xmlString = '';
+
+ for(var i=0; i<nodes.length; i++) {
+ xmlString += nodes[i].toString();
+ }
+
+ return xmlString;
+ };
+
+ // rdflib store interface
+ var store = {};
+
+ store.add = function (s, p, o ) {
+ var triple = rdf.createTriple(s, p, o);
+
+ if (filter(triple)) {
+ callback(triple);
+ }
+ };
+
+ store.bnode = function () { return rdf.createBlankNode(); };
+
+ store.literal = function (value, language, type) {
+ // parse type literal
+ if (type && type.toString() === 'http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral') {
+ value = domNodesToString(value.childNodes);
+ }
+
+ return rdf.createLiteral(value, language, type);
+ };
+
+ store.setPrefixForURI = function () {};
+
+ store.sym = function (iri) { return rdf.createNamedNode(iri); };
+
+ new RdfLibParser(store).parse(toparse, base);
+
+ done(true);
+
+ return true;
+ };
+
+ this.parse = function (toparse, callback, base, filter, graph) {
+ graph = graph || rdf.createGraph();
+
+ return this.process(
+ toparse,
+ function(triple) { graph.add(triple); },
+ base,
+ filter,
+ function(success) { callback(success ? graph : null); });
+ };
+};
+
+
+module.exports = function (rdf) {
+ rdf.RdfXmlParser = RdfXmlParser.bind(null, rdf);
+
+ var parser = new RdfXmlParser(rdf);
+ rdf.parseRdfXml = parser.parse.bind(parser);
+};
+
+},{}],11:[function(require,module,exports){
+'use strict';
+
+
+//TODO: handle blank nodes
+var SparqlStore = function (rdf, options) {
+ var
+ self = this;
+
+ options = options || {};
+
+ self.endpointUrl = options.endpointUrl;
+ self.updateUrl = options.updateUrl || self.endpointUrl;
+ self.mimeType = options.mimeType || 'text/turtle';
+ self.serialize = options.serialize || rdf.serializeNTriples;
+ self.parse = options.parse || rdf.parseTurtle;
+ self.request = options.request || rdf.defaultRequest;
+
+ var httpSuccess = function (statusCode) {
+ return (statusCode >= 200 && statusCode < 300);
+ };
+
+ var buildMatch = function (subject, predicate, object) {
+ var match = '';
+
+ var nodeToNT = function (node) {
+ if (typeof node === 'string') {
+ if (node.substr(0, 2) === '_:') {
+ return node;
+ } else {
+ return '<' + node + '>';
+ }
+ }
+
+ return node.toNT();
+ };
+
+ match += subject ? nodeToNT(subject) : '?s';
+ match += predicate ? ' ' + nodeToNT(predicate) : ' ?p';
+ match += object ? ' ' + nodeToNT(object) : ' ?o';
+
+ return match;
+ };
+
+ self.graph = function (graphIri, callback) {
+ self.match(graphIri, null, null, null, callback);
+ };
+
+ self.match = function (graphIri, subject, predicate, object, callback, limit) {
+ var
+ filter = buildMatch(subject, predicate, object),
+ query = 'CONSTRUCT { ' + filter + ' } { GRAPH <' + graphIri + '> {' + filter + ' }}',
+ url = self.endpointUrl + '?query=' + encodeURIComponent(query);
+
+ self.request('GET', url, { 'Accept': self.mimeType }, null,
+ function (statusCode, headers, resContent, error) {
+ // error during request
+ if (error) {
+ return callback(null, 'request error: ' + error);
+ }
+
+ // http status code != success
+ if (!httpSuccess(statusCode)) {
+ return callback(null, 'status code error: ' + statusCode);
+ }
+
+ // TODO: use limit parameters
+ self.parse(resContent, callback);
+ }
+ );
+ };
+
+ var updateRequest = function (content, callbackValue, callback) {
+ self.request('POST', self.updateUrl, { 'Content-Type': 'application/sparql-update' }, content,
+ function (statusCode, headers, resContent, error) {
+ // error during request
+ if (error) {
+ return callback(null, 'request error: ' + error);
+ }
+
+ // http status code != success
+ if (!httpSuccess(statusCode)) {
+ return callback(null, 'status code error: ' + statusCode);
+ }
+
+ callback(callbackValue);
+ }
+ );
+ };
+
+ self.add = function (graphIri, graph, callback) {
+ var content =
+ 'DROP SILENT GRAPH <' + graphIri + '>;' +
+ 'INSERT DATA { GRAPH <' + graphIri + '> { ' + self.serialize(graph) + ' } }';
+
+ updateRequest(content, graph, callback);
+ };
+
+ self.merge = function (graphIri, graph, callback) {
+ var content =
+ 'INSERT DATA { GRAPH <' + graphIri + '> { ' + self.serialize(graph) + ' } }';
+
+ updateRequest(content, graph, callback);
+ };
+
+ self.remove = function (graphIri, graph, callback) {
+ var content =
+ 'DELETE DATA FROM <' + graphIri + '> { ' + self.serialize(graph) + ' }';
+
+ updateRequest(content, true, callback);
+ };
+
+ self.removeMatches = function (graphIri, subject, predicate, object, callback) {
+ var content =
+ 'DELETE FROM GRAPH <' + graphIri + '> WHERE { ' +
+ buildMatch(subject, predicate, object) + ' }';
+
+ updateRequest(content, true, callback);
+ };
+
+ self.delete = function (graphIri, callback) {
+ var content = 'CLEAR GRAPH <' + graphIri + '>';
+
+ updateRequest(content, true, callback);
+ };
+};
+
+
+module.exports = function (rdf) {
+ rdf.SparqlStore = SparqlStore.bind(null, rdf);
+};
+
+},{}],12:[function(require,module,exports){
+'use strict';
+
+
+var
+ N3 = require('n3');
+
+
+var TurtleParser = function (rdf, options) {
+ options = options || {};
+
+ options.importPrefixMap = options.importPrefixMap || true;
+
+ this.process = function (data, callback, base, filter, done) {
+ var config = {};
+
+ config.documentIRI = base;
+ filter = filter || function () { return true; };
+ done = done || function () {};
+
+ var
+ parser = N3.Parser(config),
+ blankNodes = {};
+
+ parser.parse(data, function (error, n3Triple, n3Prefixes) {
+ if (error) {
+ return done(false, error);
+ }
+
+ if (options.importPrefixMap && n3Prefixes) {
+ Object.keys(n3Prefixes).forEach(function (prefix) {
+ rdf.prefixes[prefix] = n3Prefixes[prefix];
+ });
+ }
+
+ if (!n3Triple) {
+ return done(true);
+ }
+
+ var toRdfNode = function (n3Node) {
+ if (N3.Util.isIRI(n3Node)) {
+ return rdf.createNamedNode(n3Node);
+ } else if (N3.Util.isBlank(n3Node)) {
+ if (n3Node in blankNodes) {
+ return blankNodes[n3Node];
+ } else {
+ return (blankNodes[n3Node] = rdf.createBlankNode());
+ }
+ } else {
+ var
+ lang = N3.Util.getLiteralLanguage(n3Node),
+ type = N3.Util.getLiteralType(n3Node);
+
+ if (lang === '') {
+ lang = null;
+ }
+
+ if (type === 'http://www.w3.org/2001/XMLSchema#string') {
+ type = null;
+ }
+
+ return rdf.createLiteral(
+ N3.Util.getLiteralValue(n3Node),
+ lang,
+ type ? rdf.createNamedNode(type) : null);
+ }
+ };
+
+ var pushTriple = function (n3Triple) {
+ var triple = rdf.createTriple(
+ toRdfNode(n3Triple.subject),
+ toRdfNode(n3Triple.predicate),
+ toRdfNode(n3Triple.object));
+
+ if (filter(triple)) {
+ callback(triple);
+ }
+ };
+
+ pushTriple(n3Triple);
+ });
+
+ return true;
+ };
+
+ this.parse = function (data, callback, base, filter, graph) {
+ graph = graph || rdf.createGraph();
+
+ return this.process(
+ data,
+ function (triple) { graph.add(triple); },
+ base,
+ filter,
+ function (success, error) { callback(success ? graph : null, error); });
+ };
+};
+
+
+module.exports = function (rdf) {
+ rdf.TurtleParser = TurtleParser.bind(null, rdf);
+ rdf.NTriplesParser = TurtleParser.bind(null, rdf);
+
+ var parser = new TurtleParser(rdf);
+ rdf.parseTurtle = parser.parse.bind(parser);
+ rdf.parseNTriples = parser.parse.bind(parser);
+};
+
+},{"n3":47}],13:[function(require,module,exports){
+'use strict';
+
+
+var
+ N3 = require('n3');
+
+
+var TurtleSerializer = function (rdf, options) {
+ options = options || {};
+
+ options.usePrefixMap = options.usePrefixMap || true;
+
+ this.serialize = function (graph, callback) {
+ var
+ writerOptions = {},
+ writer;
+
+ callback = callback || function () {};
+
+ if (options.usePrefixMap) {
+ writerOptions.prefixes = {};
+
+ Object.keys(rdf.prefixes).forEach(function (prefix) {
+ if (typeof rdf.prefixes[prefix] !== 'string') {
+ return;
+ }
+
+ writerOptions.prefixes[prefix] = rdf.prefixes[prefix];
+ });
+ }
+
+ writer = N3.Writer(writerOptions);
+
+ var createN3Node = function (node) {
+ if (node.interfaceName.toString() === 'NamedNode') {
+ return node.nominalValue;
+ } else if (node.interfaceName.toString() === 'BlankNode') {
+ return '_:' + node.nominalValue;
+ } else {
+ if (node.datatype) {
+ return '"' + node.nominalValue + '"^^' + node.datatype.nominalValue;
+ } else if (node.language) {
+ return '"' + node.nominalValue + '"@' + node.language;
+ } else {
+ return '"' + node.nominalValue + '"';
+ }
+ }
+ };
+
+ graph.forEach(function (triple) {
+ writer.addTriple(
+ createN3Node(triple.subject),
+ createN3Node(triple.predicate),
+ createN3Node(triple.object));
+ });
+
+ writer.end(function (error, result) {
+ if (error) {
+ callback(null, error);
+ } else {
+ callback(result);
+ }
+ });
+
+ return true;
+ };
+};
+
+
+module.exports = function (rdf) {
+ rdf.TurtleSerializer = TurtleSerializer.bind(null, rdf);
+
+ var serializer = new TurtleSerializer(rdf);
+ rdf.serializeTurtle = serializer.serialize.bind(serializer);
+};
+
+},{"n3":47}],14:[function(require,module,exports){
+/* global rdf:true */
+'use strict';
+
+
+var URIResolver = function() {};
+
+URIResolver.SCHEME = /^[A-Za-z][A-Za-z0-9\+\-\.]*\:/;
+
+URIResolver.prototype.parseURI = function(uri) {
+ var match = URIResolver.SCHEME.exec(uri);
+ if (!match) {
+ throw "Bad URI value, no scheme: "+uri;
+ }
+ var parsed = { spec: uri };
+ parsed.scheme = match[0].substring(0,match[0].length-1);
+ parsed.schemeSpecificPart = parsed.spec.substring(match[0].length);
+ if (parsed.schemeSpecificPart.charAt(0)=='/' && parsed.schemeSpecificPart.charAt(1)=='/') {
+ this.parseGeneric(parsed);
+ } else {
+ parsed.isGeneric = false;
+ }
+ parsed.normalize = function() {
+ if (!this.isGeneric) {
+ return;
+ }
+ if (this.segments.length==0) {
+ return;
+ }
+ // edge case of ending in "/."
+ if (this.path.length>1 && this.path.substring(this.path.length-2)=="/.") {
+ this.path = this.path.substring(0,this.path.length-1);
+ this.segments.splice(this.segments.length-1,1);
+ this.schemeSpecificPart = "//"+this.authority+this.path;
+ if (typeof this.query != "undefined") {
+ this.schemeSpecificPart += "?" + this.query;
+ }
+ if (typeof this.fragment != "undefined") {
+ this.schemeSpecificPart += "#" + this.fragment;
+ }
+ this.spec = this.scheme+":"+this.schemeSpecificPart;
+ return;
+ }
+ var end = this.path.charAt(this.path.length-1);
+ if (end!="/") {
+ end = "";
+ }
+ for (var i=0; i<this.segments.length; i++) {
+ if (i>0 && this.segments[i]=="..") {
+ this.segments.splice(i-1,2);
+ i -= 2;
+ }
+ if (this.segments[i]==".") {
+ this.segments.splice(i,1);
+ i--;
+ }
+ }
+ this.path = this.segments.length==0 ? "/" : "/"+this.segments.join("/")+end;
+ this.schemeSpecificPart = "//"+this.authority+this.path;
+ if (typeof this.query != "undefined") {
+ this.schemeSpecificPart += "?" + this.query;
+ }
+ if (typeof this.fragment != "undefined") {
+ this.schemeSpecificPart += "#" + this.fragment;
+ }
+ this.spec = this.scheme+":"+this.schemeSpecificPart;
+ }
+ parsed.resolve = function(href) {
+ if (!href) {
+ return this.spec;
+ }
+ if (href.charAt(0)=='#') {
+ var lastHash = this.spec.lastIndexOf('#');
+ return lastHash<0 ? this.spec+href : this.spec.substring(0,lastHash)+href;
+ }
+ if (!this.isGeneric) {
+ throw "Cannot resolve uri against non-generic URI: "+this.spec;
+ }
+ var colon = href.indexOf(':');
+ if (href.charAt(0)=='/') {
+ return this.scheme+"://"+this.authority+href;
+ } else if (href.charAt(0)=='.' && href.charAt(1)=='/') {
+ if (this.path.charAt(this.path.length-1)=='/') {
+ return this.scheme+"://"+this.authority+this.path+href.substring(2);
+ } else {
+ var last = this.path.lastIndexOf('/');
+ return this.scheme+"://"+this.authority+this.path.substring(0,last)+href.substring(1);
+ }
+ } else if (URIResolver.SCHEME.test(href)) {
+ return href;
+ } else if (href.charAt(0)=="?") {
+ return this.scheme+"://"+this.authority+this.path+href;
+ } else {
+ if (this.path.charAt(this.path.length-1)=='/') {
+ return this.scheme+"://"+this.authority+this.path+href;
+ } else {
+ var last = this.path.lastIndexOf('/');
+ return this.scheme+"://"+this.authority+this.path.substring(0,last+1)+href;
+ }
+ }
+ };
+ parsed.relativeTo = function(otherURI) {
+ if (otherURI.scheme!=this.scheme) {
+ return this.spec;
+ }
+ if (!this.isGeneric) {
+ throw "A non generic URI cannot be made relative: "+this.spec;
+ }
+ if (!otherURI.isGeneric) {
+ throw "Cannot make a relative URI against a non-generic URI: "+otherURI.spec;
+ }
+ if (otherURI.authority!=this.authority) {
+ return this.spec;
+ }
+ var i=0;
+ for (; i<this.segments.length && i<otherURI.segments.length; i++) {
+ if (this.segments[i]!=otherURI.segments[i]) {
+ //alert(this.path+" different from "+otherURI.path+" at '"+this.segments[i]+"' vs '"+otherURI.segments[i]+"'");
+ var relative = "";
+ for (var j=i; j<otherURI.segments.length; j++) {
+ relative += "../";
+ }
+ for (var j=i; j<this.segments.length; j++) {
+ relative += this.segments[j];
+ if ((j+1)<this.segments.length) {
+ relative += "/";
+ }
+ }
+ if (this.path.charAt(this.path.length-1)=='/') {
+ relative += "/";
+ }
+ return relative;
+ }
+ }
+ if (this.segments.length==otherURI.segments.length) {
+ return this.hash ? this.hash : (this.query ? this.query : "");
+ } else if (i<this.segments.length) {
+ var relative = "";
+ for (var j=i; j<this.segments.length; j++) {
+ relative += this.segments[j];
+ if ((j+1)<this.segments.length) {
+ relative += "/";
+ }
+ }
+ if (this.path.charAt(this.path.length-1)=='/') {
+ relative += "/";
+ }
+ return relative;
+ } else {
+ throw "Cannot calculate a relative URI for "+this.spec+" against "+otherURI.spec;
+ }
+ };
+ return parsed;
+}
+
+URIResolver.prototype.parseGeneric = function(parsed) {
+ if (parsed.schemeSpecificPart.charAt(0)!='/' || parsed.schemeSpecificPart.charAt(1)!='/') {
+ throw "Generic URI values should start with '//':"+parsed.spec;
+ }
+
+ var work = parsed.schemeSpecificPart.substring(2);
+ var pathStart = work.indexOf("/");
+ parsed.authority = pathStart<0 ? work : work.substring(0,pathStart);
+ parsed.path = pathStart<0 ? "" : work.substring(pathStart);
+ var hash = parsed.path.indexOf('#');
+ if (hash>=0) {
+ parsed.fragment = parsed.path.substring(hash+1);
+ parsed.path = parsed.path.substring(0,hash);
+ }
+ var questionMark = parsed.path.indexOf('?');
+ if (questionMark>=0) {
+ parsed.query = parsed.path.substring(questionMark+1);
+ parsed.path = parsed.path.substring(0,questionMark);
+ }
+ if (parsed.path=="/" || parsed.path=="") {
+ parsed.segments = [];
+ } else {
+ parsed.segments = parsed.path.split(/\//);
+ if (parsed.segments.length>0 && parsed.segments[0]=='' && parsed.path.length>1 && parsed.path.charAt(1)!='/') {
+ // empty segment at the start, remove it
+ parsed.segments.shift();
+ }
+ if (parsed.segments.length>0 && parsed.path.length>0 && parsed.path.charAt(parsed.path.length-1)=='/' && parsed.segments[parsed.segments.length-1]=='') {
+ // we may have an empty the end
+ // check to see if it is legimate
+ if (parsed.path.length>1 && parsed.path.charAt(parsed.path.length-2)!='/') {
+ parsed.segments.pop();
+ }
+ }
+ // check for non-escaped characters
+ for (var i=0; i<parsed.segments.length; i++) {
+ var check = parsed.segments[i].split(/%[A-Za-z0-9][A-Za-z0-9]|[\ud800-\udfff][\ud800-\udfff]|[A-Za-z0-9\-\._~!$&'()*+,;=@:\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+/);
+
+ for (var j=0; j<check.length; j++) {
+ if (check[j].length>0) {
+ throw "Unecaped character "+check[j].charAt(0)+" ("+check[j].charCodeAt(0)+") in URI "+parsed.spec;
+ }
+ }
+ }
+ }
+ parsed.isGeneric = true;
+};
+
+
+module.exports = URIResolver;
+
+},{}],15:[function(require,module,exports){
+/* global DOMParser, XMLHttpRequest */
+'use strict';
+
+
+var utils = {};
+
+
+utils.defaultRequest = function (method, requestUrl, headers, content, callback) {
+ var xhr = new XMLHttpRequest();
+
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === xhr.DONE) {
+ var
+ headerLines = xhr.getAllResponseHeaders().split('\r\n'),
+ resHeaders = {};
+
+ for (var i = 0; i < headerLines.length; i++) {
+ var headerLine = headerLines[i].split(': ', 2);
+ resHeaders[headerLine[0].toLowerCase()] = headerLine[1];
+ }
+
+ callback(xhr.status, resHeaders, xhr.responseText);
+ }
+ };
+
+ xhr.open(method, requestUrl, true);
+
+ for (var header in headers) {
+ xhr.setRequestHeader(header, headers[header]);
+ }
+
+ xhr.send(content);
+};
+
+utils.corsProxyRequest = function (proxyUrl, method, requestUrl, headers, content, callback) {
+ var url = proxyUrl + '?url=' + encodeURIComponent(requestUrl);
+
+ utils.defaultRequest(method, url, headers, content, callback);
+};
+
+utils.parseHtml = function (toparse, base) {
+ var parser = new DOMParser();
+
+ return parser.parseFromString(toparse, 'text/html');
+};
+
+utils.parseXml = function (toparse, base) {
+ var parser = new DOMParser();
+
+ return parser.parseFromString(toparse, 'application/xml');
+};
+
+utils.mixin = function (rdf) {
+ rdf.defaultRequest = utils.defaultRequest;
+ rdf.corsProxyRequest = utils.corsProxyRequest;
+ rdf.parseHtml = utils.parseHtml;
+ rdf.parseXml = utils.parseXml;
+};
+
+
+module.exports = utils.mixin;
+
+},{}],16:[function(require,module,exports){
+'use strict';
+
+
+var utils = {};
+
+
+/*
+ * generic filters
+ */
+utils.filter = {};
+
+utils.filter.namedNode = function (node) {
+ return node.interfaceName === 'NamedNode';
+};
+
+utils.filter.blankNode = function (node) {
+ return node.interfaceName === 'BlankNode';
+};
+
+utils.filter.literal = function (node) {
+ return node.interfaceName === 'Literal';
+};
+
+utils.filter.namedNodeSubject = function (subject) {
+ return function (triple) {
+ return triple.subject.interfaceName !== 'NamedNode' || triple.subject.equals(subject);
+ };
+};
+
+
+/*
+ * list triple parts
+ */
+utils.list = {};
+
+utils.list.tripleParts = function (graph, part, filter) {
+ var nodes = {};
+
+ filter = filter || function () { return true; };
+
+ graph.forEach(function (triple) {
+ nodes[triple[part].toNT()] = triple[part];
+ });
+
+ nodes = Object.keys(nodes)
+ .map(function (key) {
+ return nodes[key];
+ })
+ .filter(function (node) {
+ return filter(node);
+ });
+
+ return nodes;
+};
+
+utils.list.subjects = function (graph, filter) {
+ return utils.list.tripleParts(graph, 'subject', filter);
+};
+
+utils.list.predicates = function (graph, filter) {
+ return utils.list.tripleParts(graph, 'predicate', filter);
+};
+
+utils.list.objects = function (graph, filter) {
+ return utils.list.tripleParts(graph, 'object', filter);
+};
+
+
+/*
+ * Creates a subgraph by traversing a graph with filter support
+ */
+utils.createSubGraph = function (rdf, graph, entry, filter) {
+ var
+ processedEntries = {},
+ subGraph = rdf.createGraph();
+
+ var processSubject = function (entries) {
+ if (entries.length === 0) {
+ return;
+ }
+
+ var
+ newEntries = [],
+ matches = rdf.createGraph();
+
+ entries.forEach(function (entry) {
+ matches.addAll(graph.match(entry));
+ });
+
+ if (filter) {
+ matches = matches.filter(filter);
+ }
+
+ matches.forEach(function (match) {
+ var key = match.object.toNT();
+
+ if (!(key in processedEntries)) {
+ newEntries.push(match.object);
+ processedEntries[key] = true;
+ }
+ });
+
+ subGraph.addAll(matches);
+
+ processSubject(newEntries);
+ };
+
+ processSubject([entry]);
+
+ return subGraph;
+};
+
+
+/*
+ * Create a subgraph based on a named node subject without crossing named node borders
+ */
+utils.createSubGraphByNamedNodeSubject = function (rdf, graph, subject) {
+ return rdf.utils.createSubGraph(graph, subject, utils.filter.namedNodeSubject(subject));
+};
+
+/*
+ * Fills a store based on createSubGraphByNamedNodeSubject for all named node subjects
+ */
+utils.splitGraphByNamedNodeSubject = function (rdf, graph, store) {
+ store = store || new rdf.promise.Store(rdf.createStore());
+
+ var adds = [];
+
+ utils.list.subjects(graph, utils.filter.namedNode).forEach(function (subject) {
+ adds.push(store.add(subject, utils.createSubGraphByNamedNodeSubject(rdf, graph, subject)));
+ });
+
+ return Promise.all(adds).then(function () {
+ return store;
+ });
+};
+
+
+/*
+ * namespace mapping
+ */
+utils.mapNamespaceNode = function (rdf, node, search, replace) {
+ // process only named nodes...
+ if (node.interfaceName !== 'NamedNode') {
+ return node;
+ }
+
+ // ...that start with search
+ if (node.nominalValue.toString().indexOf(search) !== 0) {
+ return node;
+ }
+
+ // create new named node with replace + original node without search
+ return rdf.createNamedNode(replace + node.nominalValue.toString().substr(search.length));
+};
+
+utils.mapNamespaceTriple = function (rdf, triple, search, replace) {
+ return rdf.createTriple(
+ utils.mapNamespaceNode(rdf, triple.subject, search, replace),
+ utils.mapNamespaceNode(rdf, triple.predicate, search, replace),
+ utils.mapNamespaceNode(rdf, triple.object, search, replace)
+ );
+};
+
+utils.mapNamespaceGraph = function (rdf, graph, search, replace) {
+ var mappedGraph = rdf.createGraph();
+
+ graph.forEach(function (triple) {
+ mappedGraph.add(utils.mapNamespaceTriple(rdf, triple, search, replace));
+ });
+
+ return mappedGraph;
+};
+
+
+utils.mixin = function (rdf) {
+ rdf.utils = {};
+ rdf.utils.filter = utils.filter;
+ rdf.utils.list = utils.list;
+ rdf.utils.createSubGraph = utils.createSubGraph.bind(null, rdf);
+ rdf.utils.createSubGraphByNamedNodeSubject = utils.createSubGraphByNamedNodeSubject.bind(null, rdf);
+ rdf.utils.splitGraphByNamedNodeSubject = utils.splitGraphByNamedNodeSubject.bind(null, rdf);
+ rdf.utils.mapNamespaceNode = utils.mapNamespaceNode.bind(null, rdf);
+ rdf.utils.mapNamespaceTriple = utils.mapNamespaceTriple.bind(null, rdf);
+ rdf.utils.mapNamespaceGraph = utils.mapNamespaceGraph.bind(null, rdf);
+};
+
+
+module.exports = utils.mixin;
+
+},{}],17:[function(require,module,exports){
+
+},{}],18:[function(require,module,exports){
+arguments[4][17][0].apply(exports,arguments)
+},{"dup":17}],19:[function(require,module,exports){
+/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh <fe...@feross.org> <http://feross.org>
+ * @license MIT
+ */
+
+var base64 = require('base64-js')
+var ieee754 = require('ieee754')
+var isArray = require('is-array')
+
+exports.Buffer = Buffer
+exports.SlowBuffer = SlowBuffer
+exports.INSPECT_MAX_BYTES = 50
+Buffer.poolSize = 8192 // not used by this implementation
+
+var kMaxLength = 0x3fffffff
+var rootParent = {}
+
+/**
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
+ * === true Use Uint8Array implementation (fastest)
+ * === false Use Object implementation (most compatible, even IE6)
+ *
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
+ * Opera 11.6+, iOS 4.2+.
+ *
+ * Note:
+ *
+ * - Implementation must support adding new properties to `Uint8Array` instances.
+ * Firefox 4-29 lacked support, fixed in Firefox 30+.
+ * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
+ *
+ * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
+ *
+ * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
+ * incorrect length in some situations.
+ *
+ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
+ * get the Object implementation, which is slower but will work correctly.
+ */
+Buffer.TYPED_ARRAY_SUPPORT = (function () {
+ try {
+ var buf = new ArrayBuffer(0)
+ var arr = new Uint8Array(buf)
+ arr.foo = function () { return 42 }
+ return arr.foo() === 42 && // typed array instances can be augmented
+ typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
+ new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
+ } catch (e) {
+ return false
+ }
+})()
+
+/**
+ * Class: Buffer
+ * =============
+ *
+ * The Buffer constructor returns instances of `Uint8Array` that are augmented
+ * with function properties for all the node `Buffer` API functions. We use
+ * `Uint8Array` so that square bracket notation works as expected -- it returns
+ * a single octet.
+ *
+ * By augmenting the instances, we can avoid modifying the `Uint8Array`
+ * prototype.
+ */
+function Buffer (subject, encoding) {
+ var self = this
+ if (!(self instanceof Buffer)) return new Buffer(subject, encoding)
+
+ var type = typeof subject
+ var length
+
+ if (type === 'number') {
+ length = +subject
+ } else if (type === 'string') {
+ length = Buffer.byteLength(subject, encoding)
+ } else if (type === 'object' && subject !== null) {
+ // assume object is array-like
+ if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data
+ length = +subject.length
+ } else {
+ throw new TypeError('must start with number, buffer, array or string')
+ }
+
+ if (length > kMaxLength) {
+ throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x' +
+ kMaxLength.toString(16) + ' bytes')
+ }
+
+ if (length < 0) length = 0
+ else length >>>= 0 // coerce to uint32
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ // Preferred: Return an augmented `Uint8Array` instance for best performance
+ self = Buffer._augment(new Uint8Array(length)) // eslint-disable-line consistent-this
+ } else {
+ // Fallback: Return THIS instance of Buffer (created by `new`)
+ self.length = length
+ self._isBuffer = true
+ }
+
+ var i
+ if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
+ // Speed optimization -- use set if we're copying from a typed array
+ self._set(subject)
+ } else if (isArrayish(subject)) {
+ // Tr
<TRUNCATED>
[4/7] clerezza git commit: CLEREZZA-829: using turtle-sections to
have the original version without any changes in HTML-literals
Posted by re...@apache.org.
CLEREZZA-829: using turtle-sections to have the original version without any changes in HTML-literals
Project: http://git-wip-us.apache.org/repos/asf/clerezza/repo
Commit: http://git-wip-us.apache.org/repos/asf/clerezza/commit/98a83b69
Tree: http://git-wip-us.apache.org/repos/asf/clerezza/tree/98a83b69
Diff: http://git-wip-us.apache.org/repos/asf/clerezza/diff/98a83b69
Branch: refs/heads/master
Commit: 98a83b69676a161ea6e1cb4ac4f64a2b907f5a69
Parents: bd2519d
Author: Reto Gmuer <re...@apache.org>
Authored: Sat Apr 18 09:43:47 2015 +0000
Committer: Reto Gmuer <re...@apache.org>
Committed: Sat Apr 18 09:48:38 2015 +0000
----------------------------------------------------------------------
.../tools/editor/scripts/RDFa.1.3.0.js | 40 +-
.../tools/editor/scripts/RDFaProcessor.1.3.0.js | 17 +-
.../resources/tools/editor/scripts/editor.js | 216 +
.../tools/editor/scripts/greenrdfstore.js | 11 +-
.../resources/tools/editor/scripts/rdf-ext.js | 19324 +++++++++++++++++
.../renderlets/DiscobitsContentEtch.scala | 178 +-
.../renderlets/HtmlInfoDicobitRDFaNaked.scala | 39 +-
.../renderlets/OrderedContentRDFaNaked.scala | 28 +-
.../renderlets/TitledContentRDFaNaked.scala | 51 +-
.../editor/renderlets/XmlResultWithTurtle.scala | 43 +
10 files changed, 19725 insertions(+), 222 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/clerezza/blob/98a83b69/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/RDFa.1.3.0.js
----------------------------------------------------------------------
diff --git a/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/RDFa.1.3.0.js b/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/RDFa.1.3.0.js
index 4cc83b4..7f15ed6 100644
--- a/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/RDFa.1.3.0.js
+++ b/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/RDFa.1.3.0.js
@@ -1,4 +1,4 @@
-/** @preserve green-turtle version 1.3.0 Copyright (c) 2011-2013, R. Alexander Milowski <al...@milowski.com> All rights reserved. */
+/** @preserve green-turtle version 1.3.0 Copyright (c) 2011-2014, R. Alexander Milowski <al...@milowski.com> All rights reserved. */
/**
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
@@ -1353,6 +1353,9 @@ RDFaSubject.prototype.toObject = function() {
}
}
p.objects.push({ type: object.type, value: value, language: object.language });
+ } else if (object.type==RDFaProcessor.HTMLLiteralURI) {
+ var value = object.value.length==0 ? "" : object.value[0].parentNode.innerHTML;
+ p.objects.push({ type: object.type, value: value, language: object.language });
} else {
p.objects.push({ type: object.type, value: object.value, language: object.language });
}
@@ -1416,7 +1419,6 @@ RDFaPredicate.prototype.toString = function(options) {
if (i>0) {
s += ", ";
}
- // TODO: handle HTML literal
if (this.objects[i].type=="http://www.w3.org/1999/02/22-rdf-syntax-ns#object") {
if (this.objects[i].value.substring(0,2)=="_:") {
if (options && options.filterBlankNode) {
@@ -1459,13 +1461,20 @@ RDFaPredicate.prototype.toString = function(options) {
value += this.objects[i].value[x].nodeValue;
}
}
- s += '"""'+value.replace(/"""/,"\\\"\\\"\\\"")+'"""^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral>';
+ s += '"""'+value.replace(/"""/g,"\\\"\\\"\\\"")+'"""^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral>';
+ } else if (this.objects[i].type=="http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML") {
+ // We can use innerHTML as a shortcut from the parentNode if the list is not empty
+ if (this.objects[i].value.length==0) {
+ s += '""""""^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML>';
+ } else {
+ s += '"""'+this.objects[i].value[0].parentNode.innerHTML.replace(/"""/g,"\\\"\\\"\\\"")+'"""^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML>';
+ }
} else {
var l = this.objects[i].value;
if (l.indexOf("\n")>=0 || l.indexOf("\r")>=0) {
- s += '"""' + l.replace(/"""/,"\\\"\\\"\\\"") + '"""';
+ s += '"""' + l.replace(/"""/g,"\\\"\\\"\\\"") + '"""';
} else {
- s += '"' + l.replace(/"/,"\\\"") + '"';
+ s += '"' + l.replace(/"/g,"\\\"") + '"';
}
if (this.objects[i].type!="http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral") {
s += "^^<"+this.objects[i].type+">";
@@ -2065,9 +2074,10 @@ DocumentData.prototype.merge = function(graph,options) {
}
return mapSubject ? mapSubject : u;
};
- for (var subject in graph) {
+ var subjects = typeof graph.subjects != "undefined" ? graph.subjects : graph;
+ for (var subject in subjects) {
var mapSubject = subjectMap(subject);
- var snode = graph[subject];
+ var snode = subjects[subject];
subject = mapSubject ? mapSubject : subject;
var target = this._data_.graph.subjects[subject];
if (target) {
@@ -2079,7 +2089,7 @@ DocumentData.prototype.merge = function(graph,options) {
var object = pnode.objects[i];
var toAdd = [];
for (var j=0; j<targetPredicate.objects.length; j++) {
- if (object.type==RDFaProcessor.XMLLiteralURI && (targetPredicate.objects[j].type!=object.type || targetPredicate.objects[j].value!==object.value)) {
+ if ((object.type==RDFaProcessor.XMLLiteralURI || object.type==RDFaProcessor.HTMLLiteralURI) && (targetPredicate.objects[j].type!=object.type || targetPredicate.objects[j].value!==object.value)) {
toAdd.push(object);
} else if (targetPredicate.objects[j].type!=object.type || targetPredicate.objects[j].value==object.value) {
toAdd.push(object);
@@ -2664,7 +2674,19 @@ TurtleParser.prototype.parseObject = function(subject,predicate,text) {
}
var match = this.parseLiteral(text);
if (match) {
- this.addTriple(subject,predicate,{ type: match.type ? match.type : TurtleParser.plainLiteralURI, value: match.literal, language: match.language});
+ var value = match.literal;
+ if (match.type=="http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral") {
+ var xml = "<root>"+match.literal+"</root>";
+ var parser = new DOMParser();
+ var doc = parser.parseFromString(xml,"application/xml");
+ value = doc.documentElement.childNodes;
+ } else if (match.type=="http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML") {
+ var xml = "<html><head/><body>"+match.literal+"</body></html>";
+ var parser = new DOMParser();
+ var doc = parser.parseFromString(xml,"text/html");
+ value = doc.body.childNodes;
+ }
+ this.addTriple(subject,predicate,{ type: match.type ? match.type : TurtleParser.plainLiteralURI, value: value, language: match.language});
return match.remaining;
}
this.reportError("Terminating: Cannot parse literal at "+text.substring(0,20));
http://git-wip-us.apache.org/repos/asf/clerezza/blob/98a83b69/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/RDFaProcessor.1.3.0.js
----------------------------------------------------------------------
diff --git a/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/RDFaProcessor.1.3.0.js b/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/RDFaProcessor.1.3.0.js
index 1dc3f47..1e90cc3 100644
--- a/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/RDFaProcessor.1.3.0.js
+++ b/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/RDFaProcessor.1.3.0.js
@@ -1345,6 +1345,9 @@ RDFaSubject.prototype.toObject = function() {
}
}
p.objects.push({ type: object.type, value: value, language: object.language });
+ } else if (object.type==RDFaProcessor.HTMLLiteralURI) {
+ var value = object.value.length==0 ? "" : object.value[0].parentNode.innerHTML;
+ p.objects.push({ type: object.type, value: value, language: object.language });
} else {
p.objects.push({ type: object.type, value: object.value, language: object.language });
}
@@ -1408,7 +1411,6 @@ RDFaPredicate.prototype.toString = function(options) {
if (i>0) {
s += ", ";
}
- // TODO: handle HTML literal
if (this.objects[i].type=="http://www.w3.org/1999/02/22-rdf-syntax-ns#object") {
if (this.objects[i].value.substring(0,2)=="_:") {
if (options && options.filterBlankNode) {
@@ -1451,13 +1453,20 @@ RDFaPredicate.prototype.toString = function(options) {
value += this.objects[i].value[x].nodeValue;
}
}
- s += '"""'+value.replace(/"""/,"\\\"\\\"\\\"")+'"""^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral>';
+ s += '"""'+value.replace(/"""/g,"\\\"\\\"\\\"")+'"""^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral>';
+ } else if (this.objects[i].type=="http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML") {
+ // We can use innerHTML as a shortcut from the parentNode if the list is not empty
+ if (this.objects[i].value.length==0) {
+ s += '""""""^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML>';
+ } else {
+ s += '"""'+this.objects[i].value[0].parentNode.innerHTML.replace(/"""/g,"\\\"\\\"\\\"")+'"""^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML>';
+ }
} else {
var l = this.objects[i].value;
if (l.indexOf("\n")>=0 || l.indexOf("\r")>=0) {
- s += '"""' + l.replace(/"""/,"\\\"\\\"\\\"") + '"""';
+ s += '"""' + l.replace(/"""/g,"\\\"\\\"\\\"") + '"""';
} else {
- s += '"' + l.replace(/"/,"\\\"") + '"';
+ s += '"' + l.replace(/"/g,"\\\"") + '"';
}
if (this.objects[i].type!="http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral") {
s += "^^<"+this.objects[i].type+">";
http://git-wip-us.apache.org/repos/asf/clerezza/blob/98a83b69/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/editor.js
----------------------------------------------------------------------
diff --git a/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/editor.js b/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/editor.js
new file mode 100644
index 0000000..1f18595
--- /dev/null
+++ b/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/editor.js
@@ -0,0 +1,216 @@
+function getGraphFromTurtle(callback) {
+ function getTurtleSections() {
+ var result = [];
+ var i = -1;
+ var scripts = document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "script");
+ for (var i = 0; i < scripts.length; i++) {
+ if (scripts[i] && (scripts[i].getAttribute("type") === "text/turtle")) {
+ result.push(scripts[i].text.toString());
+ }
+ }
+ return result;
+ }
+
+ function parseMultiple(turtleStrings, callback) {
+ var graph = rdf.createGraph();
+ var i = -1;
+ function processScript() {
+ i++;
+ if (i === turtleStrings.length) {
+ callback(graph);
+ }
+ var currentTurtle = turtleStrings[i];
+ //console.log('parsing ' + currentTurtle);
+ rdf.parseTurtle(currentTurtle, function (g) {
+ //console.log('parsed ' + g.toString());
+ graph.addAll(g);
+ processScript();
+ });
+ }
+ processScript();
+ }
+ var turtleSections = getTurtleSections();
+ parseMultiple(turtleSections, callback);
+
+}
+
+var discoBitsCollection = new Backbone.Collection();
+$(function () {
+
+ getGraphFromTurtle(function (origGraph) {
+ var InfoBit = Backbone.Model.extend({
+ defaults: {
+ "@type": 'disco:XHTMLInfoDiscoBit',
+ "disco:infoBit": 'Some content'
+ },
+ initialize: function () {
+ console.log('This model has been initialized.');
+ var m = this;
+ this.on('change', function (msg) {
+ console.log('A value for this model has changed: ');
+ console.log(m.changed);
+ console.log(m.get("@id"));
+ console.log('A value for this model has changed: ' + m.hasChanged(null));
+ m.foo = "bar"
+ });
+ }
+ });
+ function saveAllModified() {
+ GreenRdfStore.getGraph(document, function (newGraph) {
+ //alert("orig: "+origGraph.toNT());
+ //alert("new: "+ newGraph.toNT());
+ rdf.serializeTurtle(origGraph, function (origTurtle) {
+ rdf.serializeTurtle(newGraph, function (newTurtle) {
+ $.post("/tools/editor/post", {assert: newTurtle, revoke: origTurtle, rdfFormat: 'text/turtle'}, function (data) {
+ alert("saved");
+ origGraph = newGraph;
+ }).fail(function (data) {
+ errdata = data
+ alert("error: " + data.statusText);
+ });
+ });
+ });
+
+ });
+
+ }
+ var InfoBitView = Backbone.View.extend({
+ initialize: function () {
+ _.bindAll(this, 'save')
+ this.model.bind('save', this.save);
+ var infoBit = $(this.el).find('[property="disco:infoBit"]').html()
+ console.log(this.model.hasChanged(null))
+ //this.model.set("disco:infoBit", infoBit)
+ console.log(this.model.hasChanged(null))
+ this.stickit();
+ },
+ events: {
+ 'mousedown .editable': 'editableClick'
+ },
+ bindings: {
+ '[property="disco:infoBit"]': 'disco:infoBit'
+ },
+ editableClick: etch.editableInit,
+ save: function () {
+
+ // normally you would call model.save() here but this is a demo
+ // $(this.el).find('.editable').effect('highlight', {color: 'yellow'});
+ // $('.save-event').fadeIn('fast', function() {
+ // setTimeout($(this).fadeOut('slow'), 10000);
+ // });
+ console.log("this modified: ");
+ console.log(this.model.get("@id"));
+ console.log(this.model.changed);
+ console.log("this is modified: " + this.model.hasChanged(null));
+ saveAllModified();
+ }
+
+ });
+ //$article = $('[property="disco:infoBit"]');
+ $('[property="disco:infoBit"]').addClass("editable")
+ $('[property="disco:infoBit"]').attr("data-button-class", "all")
+ //this ensure two way binding with stickit
+ $('[property="disco:infoBit"]').attr("contenteditable", "true")
+ $('[property="disco:infoBit"]').children().attr("contenteditable", "true")
+ $article = $('[typeof="disco:XHTMLInfoDiscoBit"]');
+ _.forEach($article, function (art) {
+ console.log(art);
+ var infoBit = $(art).find('[property="disco:infoBit"]').html()
+ var about = $(art).attr('about')
+ var model = new InfoBit({
+ "@id": about,
+ "disco:infoBit": infoBit
+ });
+ new InfoBitView({model: model, el: art, tagName: art.tagName});
+ discoBitsCollection.add(model)
+ });
+
+
+
+ });
+ /*var store = rdfstore.create();
+
+ CallbackProcessor.prototype = new RDFaProcessor();
+ CallbackProcessor.prototype.constructor=RDFaProcessor;
+ function CallbackProcessor() {
+ RDFaProcessor.call(this);
+ }
+
+ CallbackProcessor.prototype.addTriple = function(origin,subject,predicate,object) {
+ alert("New triple: "+subject+", predicate "+predicate+", object "+object.value+", "+object.language+", "+object.type);
+ //RDFaProcessor.prototype.addTriple.call(this, origin, subject, predicate, object);
+ //graph.add(env.createTriple())
+ }*/
+ //var gp = new GraphRDFaProcessor();
+ /*function WrappedGraphProcessor() {
+ GraphRDFaProcessor.call(this)
+ }
+ WrappedGraphProcessor.prototype = new GraphRDFaProcessor();
+ WrappedGraphProcessor.prototype.addTriple= function(origin,subject,predicate,object) {
+ alert("uff "+origin+","+subject+","+predicate+","+object);
+ if (origin.getAttribute("content")) {
+ object.value = origin.getAttribute("content");
+ }
+ GraphRDFaProcessor.prototype.addTriple.call(this, origin, subject, predicate, object);
+ }
+ var gp = new WrappedGraphProcessor();
+ //var gp = new CallbackProcessor();
+ gp.target.graph = new RDFaGraph();
+ gp.process(document);
+ var origTurtle = gp.target.graph.toString();
+ alert(origTurtle);*/
+
+
+ //});
+
+
+
+
+
+ //var view = new articleView({model: model, el: $article[0], tagName: $article[0].tagName});
+
+});
+
+Backbone.on('all', function (s) {
+ console.log('Handling all: ' + s);
+});
+
+
+
+/*document.addEventListener(
+ "rdfa.loaded",
+ function() {
+ _.forEach(document.getElementsByType("http://discobits.org/ontology#Entry"), function(e) {
+ $(e).css('background-color', 'blue');
+ });
+ console.log('all colored');
+ //console.log('activating: '+RDFaProcessor);
+ CallbackProcessor.prototype = new RDFaProcessor();
+ CallbackProcessor.prototype.constructor=RDFaProcessor;
+ function CallbackProcessor() {
+ RDFaProcessor.call(this);
+ }
+
+ CallbackProcessor.prototype.newSubjectOrigin = function(origin,subject) {
+ console.log("New origin for "+subject);
+ }
+
+ CallbackProcessor.prototype.addTriple = function(origin,subject,predicate,object) {
+ console.log("New triple: "+subject+", predicate "+predicate+
+ ", object "+object.value+", "+object.language+", "+object.type);
+ }
+ console.log('activated: '+CallbackProcessor);
+ processor = new CallbackProcessor();
+ processor.finishedHandlers.push(
+ function(node) {
+ alert("Done!");
+ }
+ );
+ processor.process(document);
+ console.log('done');
+ },
+ false
+ );*/
+
+
+
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/98a83b69/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/greenrdfstore.js
----------------------------------------------------------------------
diff --git a/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/greenrdfstore.js b/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/greenrdfstore.js
index eef998f..5b9fe16 100644
--- a/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/greenrdfstore.js
+++ b/platform/editor/src/main/resources/META-INF/resources/tools/editor/scripts/greenrdfstore.js
@@ -6,9 +6,9 @@ function GreenRdfStore() {
}
GreenRdfStore.getGraph = function(element, callback) {
- var store = rdfstore.create();
- store.graph(function(success,graph) {
- var env = store.rdf;
+ var graph = rdf.createGraph();
+
+ var env = rdf;
CallbackProcessor.prototype = new RDFaProcessor();
CallbackProcessor.prototype.constructor=RDFaProcessor;
function CallbackProcessor() {
@@ -60,13 +60,13 @@ GreenRdfStore.getGraph = function(element, callback) {
//according to the spec this attribute should be ignored for xmlLiterals, we don't
var value = origin.getAttribute("content");
} else {
- if (object.value.length) {
+ if (object.value instanceof NodeList) {
var value = serializeNodeList(object.value);
} else {
var value = object.value;
}
}
- var objectRS = env.createLiteral(value.toString(), object.language, object.type);
+ var objectRS = env.createLiteral(value.toString(), object.language, env.createNamedNode(object.type));
}
graph.add(env.createTriple(subjectRS, predicateRS, objectRS));
};
@@ -74,5 +74,4 @@ GreenRdfStore.getGraph = function(element, callback) {
//gp.target.graph = new RDFaGraph();
gp.process(element);
callback(graph)
- });
};
\ No newline at end of file
[6/7] clerezza git commit: CLEREZZA-960: mainly renicing
Posted by re...@apache.org.
CLEREZZA-960: mainly renicing
Project: http://git-wip-us.apache.org/repos/asf/clerezza/repo
Commit: http://git-wip-us.apache.org/repos/asf/clerezza/commit/83342fb7
Tree: http://git-wip-us.apache.org/repos/asf/clerezza/tree/83342fb7
Diff: http://git-wip-us.apache.org/repos/asf/clerezza/diff/83342fb7
Branch: refs/heads/master
Commit: 83342fb773dcd833ee7e1e048bd6a7c70b17594d
Parents: 98a83b6
Author: Reto Gmuer <re...@apache.org>
Authored: Sat Apr 18 09:46:50 2015 +0000
Committer: Reto Gmuer <re...@apache.org>
Committed: Sat Apr 18 09:48:39 2015 +0000
----------------------------------------------------------------------
.../clerezza/platform/content/Editor.java | 45 +++++++++++---------
1 file changed, 25 insertions(+), 20 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/clerezza/blob/83342fb7/platform/content/src/main/java/org/apache/clerezza/platform/content/Editor.java
----------------------------------------------------------------------
diff --git a/platform/content/src/main/java/org/apache/clerezza/platform/content/Editor.java b/platform/content/src/main/java/org/apache/clerezza/platform/content/Editor.java
index f011815..095f5fa 100644
--- a/platform/content/src/main/java/org/apache/clerezza/platform/content/Editor.java
+++ b/platform/content/src/main/java/org/apache/clerezza/platform/content/Editor.java
@@ -69,7 +69,7 @@ import org.wymiwyg.commons.util.dirbrowser.PathNode;
*/
@Component
@Service(Object.class)
-@Property(name="javax.ws.rs", boolValue=true)
+@Property(name = "javax.ws.rs", boolValue = true)
@Path("tools/editor")
public class Editor extends FileServer {
@@ -78,18 +78,15 @@ public class Editor extends FileServer {
@Reference
private TcManager tcManager;
-
+
@Reference
private Serializer serializer;
-
private static final Logger logger = LoggerFactory.getLogger(Editor.class);
private Providers providers;
private final String rdfXml = "application/rdf+xml";
-
-
-
+
/**
* On activation the {@link FileServer} is prepared
*
@@ -99,7 +96,6 @@ public class Editor extends FileServer {
configure(context.getBundleContext());
}
-
/**
* The providers are injected by the Jax-rs implementation and used to
* locate readers for the RDF content of the body
@@ -111,13 +107,12 @@ public class Editor extends FileServer {
this.providers = providers;
}
-
@GET
@Path("get")
public GraphNode getDiscobit(@QueryParam("resource") IRI uri,
@QueryParam("graph") IRI graphUri) {
- final Graph mGraph = graphUri == null ? cgProvider.getContentGraph() :
- tcManager.getGraph(graphUri);
+ final Graph mGraph = graphUri == null ? cgProvider.getContentGraph()
+ : tcManager.getGraph(graphUri);
return new GraphNode(uri, mGraph);
}
@@ -125,8 +120,8 @@ public class Editor extends FileServer {
* replaces the subgraph serialized with RDF/XML in <code>revokedString
* </code> with the one from <code>assertedString</code>.
*
- * @param graphUri the graph within which the replacement has to take place or null
- * for the content graph
+ * @param graphUri the graph within which the replacement has to take place
+ * or null for the content graph
* @param assertedString the asserted ImmutableGraph as RDF/XML
* @param revokedString the revoked ImmutableGraph as RDF/XML
*/
@@ -140,7 +135,7 @@ public class Editor extends FileServer {
rdfFormat = rdfXml;
}
MediaType mediaType = MediaType.valueOf(rdfFormat);
- MessageBodyReader<ImmutableGraph> graphReader = providers.getMessageBodyReader(ImmutableGraph.class, ImmutableGraph.class, null,mediaType);
+ MessageBodyReader<ImmutableGraph> graphReader = providers.getMessageBodyReader(ImmutableGraph.class, ImmutableGraph.class, null, mediaType);
final ImmutableGraph assertedGraph;
final ImmutableGraph revokedGraph;
try {
@@ -150,13 +145,13 @@ public class Editor extends FileServer {
logger.error("reading graph {}", ex);
throw new WebApplicationException(ex, 500);
}
- final Graph mGraph = graphUri == null ? cgProvider.getContentGraph() :
- tcManager.getGraph(graphUri);
+ final Graph mGraph = graphUri == null ? cgProvider.getContentGraph()
+ : tcManager.getGraph(graphUri);
try {
- serializer.serialize(System.out, revokedGraph, "text/turtle");
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- serializer.serialize(baos, revokedGraph, "text/turtle");
- System.out.println(new String(baos.toByteArray()).contains("\r"));
+ System.out.println("Revoked:");
+ logGraph(revokedGraph);
+ System.out.println("Asserted:");
+ logGraph(assertedGraph);
GraphUtils.removeSubGraph(mGraph, revokedGraph);
} catch (NoSuchSubGraphException ex) {
throw new RuntimeException(ex);
@@ -164,6 +159,16 @@ public class Editor extends FileServer {
mGraph.addAll(assertedGraph);
}
+ private void logGraph(Graph graph) {
+ serializer.serialize(System.out, graph, "text/turtle");
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ serializer.serialize(baos, graph, "text/turtle");
+ if (new String(baos.toByteArray()).contains("\r")) {
+ System.out.println("The above graph conatins \\r");
+ }
+ System.out.println();
+ }
+
@GET
//this is to work around
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@@ -173,5 +178,5 @@ public class Editor extends FileServer {
logger.debug("serving static {}", node);
return node;
}
-
+
}
[2/7] clerezza git commit: CLEREZZA-829: using turtle-sections to
have the original version without any changes in HTML-literals
Posted by re...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/98a83b69/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/DiscobitsContentEtch.scala
----------------------------------------------------------------------
diff --git a/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/DiscobitsContentEtch.scala b/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/DiscobitsContentEtch.scala
index 36c5d15..f83de2a 100644
--- a/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/DiscobitsContentEtch.scala
+++ b/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/DiscobitsContentEtch.scala
@@ -1,4 +1,4 @@
-package org.apache.clerezza.platform.editor
+package org.apache.clerezza.platform.editor.renderlets
import org.apache.clerezza.rdf.core._
import org.apache.clerezza.rdf.scala.utils.Preamble._
@@ -23,183 +23,12 @@ abstract class DiscobitsContentEtch extends SRenderlet {
new XmlResult(arguments) {
override def content = {
val initScript = """
- var discoBitsCollection = new Backbone.Collection();
- $(function() {
-
- GreenRdfStore.getGraph(document, function(origGraph) {
- //now that we have the orig graph we no longer need the content atr
- $("span[property='disco:infoBit']").removeAttr("content");
- var InfoBit = Backbone.Model.extend({
- defaults: {
- "@type": 'disco:XHTMLInfoDiscoBit',
- "disco:infoBit": 'Some content'
- },
- initialize: function() {
- console.log('This model has been initialized.');
- var m = this;
- this.on('change', function(msg) {
- console.log('A value for this model has changed: ');
- console.log(m.changed);
- console.log(m.get("@id"));
- console.log('A value for this model has changed: '+m.hasChanged(null));
- m.foo = "bar"
- });
- }
- });
- function saveAllModified() {
- GreenRdfStore.getGraph(document, function(newGraph) {
- //alert("orig: "+origGraph.toNT());
- //alert("new: "+ newGraph.toNT());
- $.post( "/tools/editor/post", { assert: newGraph.toNT(), revoke: origGraph.toNT(), rdfFormat: 'text/turtle' }, function( data ) {
- alert("saved");
- origTurtle = newTurtle;
- }) .fail(function( data) {
- errdata = data
- alert( "error: " + data.statusText);
- });
- });
-
- }
- var InfoBitView = Backbone.View.extend({
- initialize: function() {
- _.bindAll(this, 'save')
- this.model.bind('save', this.save);
- var infoBit = $(this.el).find('[property="disco:infoBit"]').html()
- console.log(this.model.hasChanged(null))
- //this.model.set("disco:infoBit", infoBit)
- console.log(this.model.hasChanged(null))
- this.stickit();
- },
- events: {
- 'mousedown .editable': 'editableClick'
- },
- bindings: {
- '[property="disco:infoBit"]': 'disco:infoBit'
- },
- editableClick: etch.editableInit,
- save: function() {
-
- // normally you would call model.save() here but this is a demo
- // $(this.el).find('.editable').effect('highlight', {color: 'yellow'});
- // $('.save-event').fadeIn('fast', function() {
- // setTimeout($(this).fadeOut('slow'), 10000);
- // });
- console.log("this modified: ");
- console.log(this.model.get("@id"));
- console.log(this.model.changed);
- console.log("this is modified: "+this.model.hasChanged(null));
- saveAllModified();
- }
-
- });
- //$article = $('[property="disco:infoBit"]');
- $('[property="disco:infoBit"]').addClass("editable")
- $('[property="disco:infoBit"]').attr("data-button-class", "all")
- //this ensure two way binding with stickit
- $('[property="disco:infoBit"]').attr("contenteditable", "true")
- $article = $('[typeof="disco:XHTMLInfoDiscoBit"]');
- _.forEach($article, function(art) {
- console.log(art);
- var infoBit = $(art).find('[property="disco:infoBit"]').html()
- var about = $(art).attr('about')
- var model = new InfoBit({
- "@id": about,
- "disco:infoBit": infoBit
- });
- new InfoBitView({model: model, el: art, tagName: art.tagName});
- discoBitsCollection.add(model)
- });
-
-
-
- });
- /*var store = rdfstore.create();
-
- CallbackProcessor.prototype = new RDFaProcessor();
- CallbackProcessor.prototype.constructor=RDFaProcessor;
- function CallbackProcessor() {
- RDFaProcessor.call(this);
- }
-
- CallbackProcessor.prototype.addTriple = function(origin,subject,predicate,object) {
- alert("New triple: "+subject+", predicate "+predicate+", object "+object.value+", "+object.language+", "+object.type);
- //RDFaProcessor.prototype.addTriple.call(this, origin, subject, predicate, object);
- //graph.add(env.createTriple())
- }*/
- //var gp = new GraphRDFaProcessor();
- /*function WrappedGraphProcessor() {
- GraphRDFaProcessor.call(this)
- }
- WrappedGraphProcessor.prototype = new GraphRDFaProcessor();
- WrappedGraphProcessor.prototype.addTriple= function(origin,subject,predicate,object) {
- alert("uff "+origin+","+subject+","+predicate+","+object);
- if (origin.getAttribute("content")) {
- object.value = origin.getAttribute("content");
- }
- GraphRDFaProcessor.prototype.addTriple.call(this, origin, subject, predicate, object);
- }
- var gp = new WrappedGraphProcessor();
- //var gp = new CallbackProcessor();
- gp.target.graph = new RDFaGraph();
- gp.process(document);
- var origTurtle = gp.target.graph.toString();
- alert(origTurtle);*/
-
-
- //});
-
-
-
-
-
- //var view = new articleView({model: model, el: $article[0], tagName: $article[0].tagName});
-
- });
-
- Backbone.on('all', function(s) {
- console.log('Handling all: ' + s);
- });
-
-
- /*document.addEventListener(
- "rdfa.loaded",
- function() {
- _.forEach(document.getElementsByType("http://discobits.org/ontology#Entry"), function(e) {
- $(e).css('background-color', 'blue');
- });
- console.log('all colored');
- //console.log('activating: '+RDFaProcessor);
- CallbackProcessor.prototype = new RDFaProcessor();
- CallbackProcessor.prototype.constructor=RDFaProcessor;
- function CallbackProcessor() {
- RDFaProcessor.call(this);
- }
-
- CallbackProcessor.prototype.newSubjectOrigin = function(origin,subject) {
- console.log("New origin for "+subject);
- }
-
- CallbackProcessor.prototype.addTriple = function(origin,subject,predicate,object) {
- console.log("New triple: "+subject+", predicate "+predicate+
- ", object "+object.value+", "+object.language+", "+object.type);
- }
- console.log('activated: '+CallbackProcessor);
- processor = new CallbackProcessor();
- processor.finishedHandlers.push(
- function(node) {
- alert("Done!");
- }
- );
- processor.process(document);
- console.log('done');
- },
- false
- );*/
"""
val html = <html xmlns:disco="http://discobits.org/ontology#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<head>
+ <meta charset="utf-8"/>
<link type="text/css" href="/style/style.css" rel="stylesheet" />
<link rel="stylesheet" href="/tools/editor/styles/etch.css" />
{for (part <- res/DISCOBITS.contains; if ((part/DISCOBITS.pos*) == "0")) yield
@@ -214,8 +43,9 @@ abstract class DiscobitsContentEtch extends SRenderlet {
<script src="/tools/editor/scripts/backbone-min.js"></script>
<script src="/tools/editor/scripts/etch.js"></script>
<script src="/tools/editor/scripts/backbone.stickit.js"></script>
- <script src="/tools/editor/scripts/rdfstore.js" type="text/javascript"></script>
+ <script src="/tools/editor/scripts/rdf-ext.js" type="text/javascript"></script>
<script src="/tools/editor/scripts/greenrdfstore.js"></script>
+ <script src="/tools/editor/scripts/editor.js" type="text/javascript"></script>
<script>
{Unparsed(initScript)}
</script>
http://git-wip-us.apache.org/repos/asf/clerezza/blob/98a83b69/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/HtmlInfoDicobitRDFaNaked.scala
----------------------------------------------------------------------
diff --git a/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/HtmlInfoDicobitRDFaNaked.scala b/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/HtmlInfoDicobitRDFaNaked.scala
index 5e64b41..dc116af 100644
--- a/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/HtmlInfoDicobitRDFaNaked.scala
+++ b/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/HtmlInfoDicobitRDFaNaked.scala
@@ -1,32 +1,49 @@
-package org.apache.clerezza.platform.editor
-
+package org.apache.clerezza.platform.editor.renderlets
import org.apache.clerezza.rdf.core._
import org.apache.clerezza.rdf.scala.utils.Preamble._
+import java.io.ByteArrayOutputStream
import javax.ws.rs.core.MediaType
+import org.apache.clerezza.commons.rdf.BlankNodeOrIRI
+import org.apache.clerezza.commons.rdf.Graph
+import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl
+import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph
import org.apache.clerezza.platform.typerendering.TypeRenderlet
import org.apache.clerezza.platform.typerendering.scala._
+import org.apache.clerezza.rdf.core.serializedform.Serializer
import org.apache.clerezza.rdf.ontologies.DISCOBITS
+import org.apache.clerezza.rdf.ontologies.RDF
import org.apache.felix.scr.annotations.Component;
-import org.apache.felix.scr.annotations.Service;import scala.xml.Unparsed
-
+import org.apache.felix.scr.annotations.Service;
+import org.apache.felix.scr.annotations.Reference;
+import scala.xml.NodeBuffer
+import scala.xml.Unparsed;
@Component
@Service(Array(classOf[TypeRenderlet]))
class HtmlInfoDicobitRDFaNaked extends SRenderlet {
- val getRdfType = DISCOBITS.XHTMLInfoDiscoBit
-
+ @Reference
+ var serializer: Serializer = null;
+
+ val getRdfType = DISCOBITS.XHTMLInfoDiscoBit
+
override val getMediaType = MediaType.TEXT_HTML_TYPE
override def getModePattern = "rdfa-naked"
override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- override def content = {
- <div typeof="disco:XHTMLInfoDiscoBit" about={res*}>
- <span property="disco:infoBit" content={(res/DISCOBITS.infoBit*).replace("\n","\\n")} datatype="rdf:XMLLiteral">{Unparsed(res/DISCOBITS.infoBit*)}</span>
- </div>
+ new XmlResultWithTurtle(arguments, serializer) {
+
+ override def addTriples(shownGraph : Graph) {
+ shownGraph.add(new TripleImpl((res!).asInstanceOf[BlankNodeOrIRI], RDF.`type`, DISCOBITS.XHTMLInfoDiscoBit));
+ shownGraph.add(new TripleImpl((res!).asInstanceOf[BlankNodeOrIRI], DISCOBITS.infoBit, res / DISCOBITS.infoBit!));
+ }
+
+ override def specificContent = {
+ <div typeof="disco:XHTMLInfoDiscoBit" about={ res* }>
+ <span property="disco:infoBit" datatype="rdf:XMLLiteral">{ Unparsed(res / DISCOBITS.infoBit*) }</span>
+ </div>
}
}
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/98a83b69/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/OrderedContentRDFaNaked.scala
----------------------------------------------------------------------
diff --git a/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/OrderedContentRDFaNaked.scala b/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/OrderedContentRDFaNaked.scala
index e8e00f5..fbbba2b 100644
--- a/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/OrderedContentRDFaNaked.scala
+++ b/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/OrderedContentRDFaNaked.scala
@@ -1,19 +1,29 @@
-package org.apache.clerezza.platform.editor
+package org.apache.clerezza.platform.editor.renderlets
import org.apache.clerezza.rdf.core._
import org.apache.clerezza.rdf.scala.utils.Preamble._
import javax.ws.rs.core.MediaType
+import org.apache.clerezza.commons.rdf.BlankNode
+import org.apache.clerezza.commons.rdf.BlankNodeOrIRI
+import org.apache.clerezza.commons.rdf.Graph
+import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl
import org.apache.clerezza.platform.typerendering.TypeRenderlet
import org.apache.clerezza.platform.typerendering.scala._
+import org.apache.clerezza.rdf.core.serializedform.Serializer
import org.apache.clerezza.rdf.ontologies.DISCOBITS
+import org.apache.clerezza.rdf.ontologies.RDF
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
+import org.apache.felix.scr.annotations.Reference;
@Component
@Service(Array(classOf[TypeRenderlet]))
class OrderedContentRDFaNaked extends SRenderlet {
+ @Reference
+ var serializer: Serializer = null;
+
val getRdfType = DISCOBITS.OrderedContent
override val getMediaType = MediaType.TEXT_HTML_TYPE
@@ -21,8 +31,20 @@ class OrderedContentRDFaNaked extends SRenderlet {
override def getModePattern = "rdfa-naked"
override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- override def content = {
+ new XmlResultWithTurtle(arguments, serializer) {
+
+ override def addTriples(shownGraph : Graph) {
+ shownGraph.add(new TripleImpl((res!).asInstanceOf[BlankNodeOrIRI], RDF.`type`, DISCOBITS.OrderedContent));
+ for (part <- res/DISCOBITS.contains) {
+ val entry = new BlankNode
+ shownGraph.add(new TripleImpl((res!).asInstanceOf[BlankNodeOrIRI], DISCOBITS.contains, entry));
+ shownGraph.add(new TripleImpl(entry, RDF.`type`, DISCOBITS.Entry));
+ shownGraph.add(new TripleImpl(entry, DISCOBITS.pos, part/DISCOBITS.pos!));
+ shownGraph.add(new TripleImpl(entry, DISCOBITS.holds, part/DISCOBITS.holds!));
+ }
+ }
+
+ override def specificContent = {
<div about={res*} typeof="disco:OrderedContent">
{for (part <- (res/DISCOBITS.contains).sortBy(part => (part/DISCOBITS.pos*).toInt))
yield <div property="disco:contains" typeof="disco:Entry">
http://git-wip-us.apache.org/repos/asf/clerezza/blob/98a83b69/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/TitledContentRDFaNaked.scala
----------------------------------------------------------------------
diff --git a/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/TitledContentRDFaNaked.scala b/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/TitledContentRDFaNaked.scala
index 94e29fd..f817350 100644
--- a/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/TitledContentRDFaNaked.scala
+++ b/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/TitledContentRDFaNaked.scala
@@ -1,19 +1,29 @@
-package org.apache.clerezza.platform.editor
+package org.apache.clerezza.platform.editor.renderlets
import org.apache.clerezza.rdf.core._
import org.apache.clerezza.rdf.scala.utils.Preamble._
import javax.ws.rs.core.MediaType
+import org.apache.clerezza.commons.rdf.BlankNode
+import org.apache.clerezza.commons.rdf.BlankNodeOrIRI
+import org.apache.clerezza.commons.rdf.Graph
+import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl
import org.apache.clerezza.platform.typerendering.TypeRenderlet
import org.apache.clerezza.platform.typerendering.scala._
+import org.apache.clerezza.rdf.core.serializedform.Serializer
import org.apache.clerezza.rdf.ontologies.DISCOBITS
+import org.apache.clerezza.rdf.ontologies.RDF
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
+import org.apache.felix.scr.annotations.Reference;
@Component
@Service(Array(classOf[TypeRenderlet]))
class TitledContentRDFaNaked extends SRenderlet {
+ @Reference
+ var serializer: Serializer = null;
+
val getRdfType = DISCOBITS.TitledContent
override val getMediaType = MediaType.TEXT_HTML_TYPE
@@ -21,22 +31,33 @@ class TitledContentRDFaNaked extends SRenderlet {
override def getModePattern = "rdfa-naked"
override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- override def content = {
- <div typeof="disco:TitledContent" about={res*}>
+ new XmlResultWithTurtle(arguments, serializer) {
+
+ override def addTriples(shownGraph : Graph) {
+ shownGraph.add(new TripleImpl((res!).asInstanceOf[BlankNodeOrIRI], RDF.`type`, DISCOBITS.TitledContent));
+ for (part <- res/DISCOBITS.contains) {
+ val entry = new BlankNode
+ shownGraph.add(new TripleImpl((res!).asInstanceOf[BlankNodeOrIRI], DISCOBITS.contains, entry));
+ shownGraph.add(new TripleImpl(entry, RDF.`type`, DISCOBITS.Entry));
+ shownGraph.add(new TripleImpl(entry, DISCOBITS.pos, part/DISCOBITS.pos!));
+ shownGraph.add(new TripleImpl(entry, DISCOBITS.holds, part/DISCOBITS.holds!));
+ }
+ }
+
+ override def specificContent = {
+ <div typeof="disco:TitledContent" about={res*}>
{for (part <- res/DISCOBITS.contains; if ((part/DISCOBITS.pos*) == "0"))
yield <span property="disco:contains" typeof="disco:Entry">
- <span property="disco:pos" style="display: none">0</span>
- <h1 resource={part/DISCOBITS.holds*} property="disco:holds">{render(part/DISCOBITS.holds, "rdfa-naked")}</h1>
- </span>}
- {for (part <- res/DISCOBITS.contains; if ((part/DISCOBITS.pos*) == "1"))
- yield <div property="disco:contains" typeof="disco:Entry">
- <div property="disco:pos" style="display: none">{part/DISCOBITS.pos*}</div>
- <div property="disco:holds" resource={part/DISCOBITS.holds*}>{render(part/DISCOBITS.holds, "rdfa-naked")}</div>
- </div>}
- </div>
+ <span property="disco:pos" style="display: none">0</span>
+ <h1 resource={part/DISCOBITS.holds*} property="disco:holds">{render(part/DISCOBITS.holds, "rdfa-naked")}</h1>
+ </span>}
+ {for (part <- res/DISCOBITS.contains; if ((part/DISCOBITS.pos*) == "1"))
+ yield <div property="disco:contains" typeof="disco:Entry">
+ <div property="disco:pos" style="display: none">{part/DISCOBITS.pos*}</div>
+ <div property="disco:holds" resource={part/DISCOBITS.holds*}>{render(part/DISCOBITS.holds, "rdfa-naked")}</div>
+ </div>}
+ </div>
+ }
}
- }
}
-
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/98a83b69/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/XmlResultWithTurtle.scala
----------------------------------------------------------------------
diff --git a/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/XmlResultWithTurtle.scala b/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/XmlResultWithTurtle.scala
new file mode 100644
index 0000000..fcdeba9
--- /dev/null
+++ b/platform/editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/XmlResultWithTurtle.scala
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2015 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.clerezza.platform.editor.renderlets
+
+import java.io.ByteArrayOutputStream
+import org.apache.clerezza.commons.rdf.Graph
+import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph
+import org.apache.clerezza.platform.typerendering.scala.XmlResult
+import org.apache.clerezza.rdf.core.serializedform.Serializer
+import org.apache.clerezza.rdf.core.serializedform.SupportedFormat
+import scala.xml.NodeBuffer
+import scala.xml.Unparsed
+
+abstract class XmlResultWithTurtle(arguments: XmlResult.Arguments, serializer: Serializer) extends XmlResult(arguments) {
+ override def content = {
+ val shownGraph = new SimpleGraph
+ addTriples(shownGraph)
+ val serializedOut = new ByteArrayOutputStream;
+ serializer.serialize(serializedOut, shownGraph, SupportedFormat.TURTLE)
+ val turtle = new String(serializedOut.toByteArray, "UTF-8");
+ new NodeBuffer() &+ <script type="text/turtle">
+ { Unparsed(turtle) }
+ </script> &+ specificContent
+
+ }
+ def addTriples(shownGraph: Graph): Unit;
+
+ def specificContent: AnyRef;
+}
[5/7] clerezza git commit: CLEREZZA-988: returning Unparsed instead
of a parse XML-Sequence
Posted by re...@apache.org.
CLEREZZA-988: returning Unparsed instead of a parse XML-Sequence
Project: http://git-wip-us.apache.org/repos/asf/clerezza/repo
Commit: http://git-wip-us.apache.org/repos/asf/clerezza/commit/bd2519d6
Tree: http://git-wip-us.apache.org/repos/asf/clerezza/tree/bd2519d6
Diff: http://git-wip-us.apache.org/repos/asf/clerezza/diff/bd2519d6
Branch: refs/heads/master
Commit: bd2519d672205bb8ca68cc1f236557df3e027f4a
Parents: 51eade1
Author: Reto Gmuer <re...@apache.org>
Authored: Sat Apr 18 09:35:58 2015 +0000
Committer: Reto Gmuer <re...@apache.org>
Committed: Sat Apr 18 09:48:38 2015 +0000
----------------------------------------------------------------------
.../clerezza/platform/typerendering/scala/XmlResult.scala | 10 ++--------
1 file changed, 2 insertions(+), 8 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bd2519d6/platform/typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/XmlResult.scala
----------------------------------------------------------------------
diff --git a/platform/typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/XmlResult.scala b/platform/typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/XmlResult.scala
index c291bdf..0ac21a0 100644
--- a/platform/typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/XmlResult.scala
+++ b/platform/typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/XmlResult.scala
@@ -73,12 +73,9 @@ abstract class XmlResult(arguments: XmlResult.Arguments) {
}
def render(resource: GraphNode, mode: String) = {
- def parseNodeSeq(string: String) = {
- _root_.scala.xml.XML.loadString("<elem>" + string + "</elem>").child
- }
val baos = new java.io.ByteArrayOutputStream
renderer.render(resource, context, mode, baos)
- parseNodeSeq(new String(baos.toByteArray, UTF8))
+ Unparsed(new String(baos.toByteArray, UTF8))
}
/**
@@ -97,12 +94,9 @@ abstract class XmlResult(arguments: XmlResult.Arguments) {
* rendered by the caller but getting a new context using the GraphNodeProvider
*/
def render(resource: IRI, mode: String) = {
- def parseNodeSeq(string: String) = {
- _root_.scala.xml.XML.loadString("<elem>" + string + "</elem>").child
- }
val baos = new java.io.ByteArrayOutputStream
renderer.render(resource, context, mode, baos)
- parseNodeSeq(new String(baos.toByteArray, UTF8))
+ Unparsed(new String(baos.toByteArray, UTF8))
}
/**