return function (bindings) {
   // Evaluate the arguments
   var args = new Array(argumentExpressions.length),
       origArgs = new Array(argumentExpressions.length);
   for (var i = 0; i < argumentExpressions.length; i++) {
     var arg = args[i] = origArgs[i] = argumentExpressions[i](bindings);
     // If any argument is undefined, the result is undefined
     if (arg === undefined) return;
     // Convert the arguments if necessary
     switch (operator.type) {
     case 'numeric':
       args[i] = parseFloat(N3Util.getLiteralValue(arg));
       break;
     case 'boolean':
       args[i] = arg !== XSD_FALSE &&
                (!N3Util.isLiteral(arg) || N3Util.getLiteralValue(arg) !== '0');
       break;
     }
   }
   // Call the operator on the evaluated arguments
   var result = operator.apply(null, args);
   // Convert result if necessary
   switch (operator.resultType) {
   case 'numeric':
     // TODO: determine type instead of taking the type of the first argument
     var type = N3Util.getLiteralType(origArgs[0]) || XSD_INTEGER;
     return '"' + result + '"^^' + type;
   case 'boolean':
     return result ? XSD_TRUE : XSD_FALSE;
   default:
     return result;
   }
 };
      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);
        }
      };
Пример #3
0
function getValue(uri) {
	var value = null;
	if (N3Util.isLiteral(uri)) {
		value = N3Util.getLiteralValue(uri);
	}
	return value;
}
Пример #4
0
var term = function (str) {
    if (N3.Util.isBlank(str)) {
        return {
            type: 'blank node',
            value: str
        };
    } else if (N3.Util.isLiteral(str)) {
        var ret = {
            type: 'literal',
            value: N3.Util.getLiteralValue(str),
            datatype: N3.Util.getLiteralType(str),
        };

        var language = N3.Util.getLiteralLanguage(str);
        if (language !== '') {
            ret.language = language;
        }

        return ret;
    } else {
        return {
            type: 'IRI',
            value: str
        };
    }
};
Пример #5
0
exports.sanitizeUsingPolicy = function(text, options) {
  var val = n3util.getLiteralValue(text),
      type = n3util.getLiteralType(text),
      ret = '"' + sanitize(val,options) + '"';
  if (type) {
    ret += '^^' + type;
  }
  return ret;
};
Пример #6
0
exports.removeMarkup = function (text) {
  var val = n3util.getLiteralValue(text),
      type = n3util.getLiteralType(text),  
      ret = '"' + sanitize(val, {allowedTags:[]}) + '"';
  if (type) {
    ret += '^^' + type;
  }
  return ret;
};
Пример #7
0
 var ii = function (triple) {
   if (n3util.isBlank(triple.subject)) {
     triple.subject = _blank(this, triple.subject);
   }
   if (n3util.isBlank(triple.object)) {
     triple.object = _blank(this, triple.object);
   }
   document.triples.push(triple);
 };
Пример #8
0
// Converts a triple to the JSON-LD library representation
function toJsonLdTriple(subject, predicate, object) {
  return {
    subject:   { value: subject,   type: subject[0]   !== '_' ? 'IRI' : 'blank node' },
    predicate: { value: predicate, type: predicate[0] !== '_' ? 'IRI' : 'blank node' },
    object: !N3.Util.isLiteral(object) ?
               { value: object,    type: object[0]    !== '_' ? 'IRI' : 'blank node' } :
               { value:    N3.Util.getLiteralValue(object),
                 datatype: N3.Util.getLiteralType(object),
                 language: N3.Util.getLiteralLanguage(object) },
  };
}
Пример #9
0
SubjectService.prototype._composeTriples = function(id, params) {
    var triples = [];
    var uniqueUri = id || generateUri('student#', params.name);
    triples.push(createTriple(uniqueUri, rdf.type, custom.subject.Subject));

    if (params.name) {
        triples.push(createTriple(uniqueUri, custom.subject.name, N3Util.createLiteral(params.name)));
    }
    if (params.field) {
        triples.push(createTriple(uniqueUri, custom.subject.field, N3Util.createLiteral(params.field)));
    }

    return triples;
};
 function toTripleObject(n3Object) {
   var object = {};
   if (n3.Util.isLiteral(n3Object)) {
     object.value = n3.Util.getLiteralValue(n3Object);
     object.type = n3.Util.getLiteralType(n3Object);
   } else {
     if (n3.Util.isIRI(n3Object)) {
       object.id = expandPrefixedName(n3Object, prefixes);
     } else {
       object.id = n3Object;
     }
   }
   return object;
 }
Пример #11
0
// Creates a triple in the JSON-LD library representation
function createTriple(subject, predicate, object, context) {
  var triple = {
    subject:   { value: subject,   type: subject[0]   !== '_' ? 'IRI' : 'blank node' },
    predicate: { value: predicate, type: predicate[0] !== '_' ? 'IRI' : 'blank node' },
    object: !N3Util.isLiteral(object) ?
               { value: object,    type: object[0]    !== '_' ? 'IRI' : 'blank node' } :
               { value:    N3Util.getLiteralValue(object),
                 datatype: N3Util.getLiteralType(object),
                 language: N3Util.getLiteralLanguage(object) },
  };
  if (context && this._patternFields.indexOf('context') >= 0) {
      triple = { 'graph': context, 'triple': triple };
  }
  return triple;
}
Пример #12
0
SparqlDatasource.prototype._createTriplePattern = function (triple) {
  var query = ['{'], literalMatch;

  // Add a possible subject IRI
  triple.subject ? query.push('<', triple.subject, '> ') : query.push('?s ');

  // Add a possible predicate IRI
  triple.predicate ? query.push('<', triple.predicate, '> ') : query.push('?p ');

  // Add a possible object IRI or literal
  if (N3.Util.isUri(triple.object))
    query.push('<', triple.object, '>');
  else if (!(literalMatch = /^"([^]*)"(?:(@[^"]+)|\^\^([^"]+))?$/.exec(triple.object)))
    query.push('?o');
  else {
    if (!/["\\]/.test(literalMatch[1]))
      query.push('"', literalMatch[1], '"');
    else
      query.push('"""', literalMatch[1].replace(/(["\\])/g, '\\$1'), '"""');
    literalMatch[2] ? query.push(literalMatch[2]) :
    literalMatch[3] && query.push('^^<', literalMatch[3], '>');
  }

  return query.push('}'), query.join('');
};
Пример #13
0
 function val (term, mapping) {
   mapping = mapping || m;                     // Mostly used for left→right mappings.
   if (n3.Util.isBlank(term))
     return (term in mapping) ? mapping[term] : null // Bnodes get current binding or null.
   else
     return term;                              // Other terms evaluate to themselves.
 }
  function (request, query, datasourceSettings) {
  // TODO: these URLs should be generated by the routers
  var requestUrl = request.parsedUrl,
      paramsNoPage = _.omit(requestUrl.query, 'page'),
      currentPage = parseInt(requestUrl.query.page, 10) || 1,
      datasourceUrl = url.format(_.omit(requestUrl, 'search', 'query')),
      fragmentUrl = url.format(_.defaults({ search: '', query: paramsNoPage }, requestUrl)),
      fragmentPageUrlBase = fragmentUrl + (/\?/.test(fragmentUrl) ? '&' : '?') + 'page=',
      indexUrl = url.format(_.omit(requestUrl, 'search', 'query', 'pathname')) + '/';

  // Generate a textual representation of the pattern
  query.patternString = '{ ' +
    (query.subject              ? '<' + query.subject   + '> ' : '?s ') +
    (query.predicate            ? '<' + query.predicate + '> ' : '?p ') +
    (N3Util.isIRI(query.object) ? '<' + query.object    + '> ' : (query.object || '?o')) + ' }';

  return {
    datasource: _.assign(_.omit(datasourceSettings, 'datasource'), {
      index: indexUrl + '#dataset',
      url: datasourceUrl + '#dataset',
      templateUrl: datasourceUrl + '{?subject,predicate,object}',
    }),
    fragment: {
      url: fragmentUrl,
      pageUrl: url.format(requestUrl),
      firstPageUrl: fragmentPageUrlBase + '1',
      nextPageUrl: fragmentPageUrlBase + (currentPage + 1),
      previousPageUrl: currentPage > 1 ? fragmentPageUrlBase + (currentPage - 1) : null,
    },
    query: query,
    prefixes: this._prefixes,
    datasources: this._datasources,
  };
};
function expandPrefixedName(name, prefixes) {
  try {
    return n3.Util.expandPrefixedName(name, prefixes);
  } catch (e) {
    return name;
  }
}
Пример #16
0
FieldService.prototype._composeTriples = function(id, params) {
    var triples = [];
    var uniqueUri = id || generateUri(custom.field.Field, params.name);
    triples.push(createTriple(uniqueUri, rdf.type, custom.field.Field));

    if (params.name) {
        triples.push(createTriple(uniqueUri, custom.field.name, N3Util.createLiteral(params.name)));
    }
    return triples;
};
Пример #17
0
 meta: function (s, p, o) {
   // Relate the metadata graph to the data
   if (supportsGraphs && !metadataGraph) {
     metadataGraph = settings.metadataGraph;
     writer.addTriple(metadataGraph, primaryTopic, settings.fragmentUrl, metadataGraph);
   }
   // Write the triple
   if (s && p && o && !N3.Util.isLiteral(s))
     writer.addTriple(s, p, o, metadataGraph);
 },
Пример #18
0
 self.metadata().then(function (info) {
     var dc_title = N3.Util.getLiteralValue(info.get('dc:title'));
     if (self._container && self._container.State.Running) {
         var since = new Date(self._container.State.StartedAt);
         var running = '(running ' + interval_to_human(new Date() - since) + ')';
         console.log(status.running, tag, id.grey, padding, dc_title.bold.white,
                    running.blue);
     } else {
         console.log(status.stopped, tag, id.grey, padding, dc_title.bold.white);
     }
 }).catch(function (err) {
Пример #19
0
StudentService.prototype._composeTriples = function(id, params) {
    var triples = [];
    console.log(params.firstName);
    var uniqueUri = id || generateUri('student#',
        params.firstName+ params.lastName);

    triples.push(createTriple(uniqueUri, rdf.type, custom.student.Student));
    triples.push(createTriple(uniqueUri, custom.vocab.fullName, N3Util.createLiteral(params.firstName + ' ' + params.lastName)));

    if (params.firstName) {
        triples.push(createTriple(uniqueUri, custom.vocab.firstName, N3Util.createLiteral(params.firstName)));
    }
    if (params.lastName) {
        triples.push(createTriple(uniqueUri, custom.vocab.lastName, N3Util.createLiteral(params.lastName)));
    }
    if (params.dateOfBirth) {
        triples.push(createTriple(uniqueUri, custom.vocab.dateOfBirth, N3Util.createLiteral(params.dateOfBirth)));
    }
    if (params.mobilePhone) {
        triples.push(createTriple(uniqueUri, custom.vocab.mobilePhone, N3Util.createLiteral(params.mobilePhone)));
    }
    if (params.email) {
        triples.push(createTriple(uniqueUri, custom.vocab.email, N3Util.createLiteral(params.email)));
    }
    if (params.belongsToGroup) {
        triples.push(createTriple(uniqueUri, custom.student.belongsToGroup, params.belongsToGroup));
    }

    return triples;
};
Пример #20
0
TeacherService.prototype._composeTriples = function(id, params) {
    var triples = [];
    var uniqueUri = id || generateUri(custom.teacher.Teacher, params.firstName + params.lastName);
    triples.push(createTriple(uniqueUri, rdf.type, custom.teacher.Teacher));
    triples.push(createTriple(uniqueUri, custom.vocab.fullName, params.firstName + ' ' + params.lastName));

    if (params.firstName) {
        triples.push(createTriple(uniqueUri, custom.vocab.firstName, N3Util.createLiteral(params.firstName)));
    }
    if (params.lastName) {
        triples.push(createTriple(uniqueUri, custom.vocab.lastName, N3Util.createLiteral(params.lastName)));
    }
    if (params.dateOfBirth) {
        triples.push(createTriple(uniqueUri, custom.vocab.dateOfBirth, N3Util.createLiteral(params.dateOfBirth)));
    }
    if (params.mobilePhone) {
        triples.push(createTriple(uniqueUri, custom.vocab.mobilePhone, N3Util.createLiteral(params.mobilePhone)));
    }
    if (params.email) {
        triples.push(createTriple(uniqueUri, custom.vocab.email, N3Util.createLiteral(params.email)));
    }
    if (params.teachesSubject) {
        triples.push(createTriple(uniqueUri, custom.teacher.teachesSubject, params.teachesSubject));
    }
    if (params.title) {
        triples.push(createTriple(uniqueUri, custom.teacher.title, N3Util.createLiteral(params.title)));
    }

    return triples;
};
Пример #21
0
        streamTriples(ldfURL, function(err, triple) {
            if (err) {
                console.log("Error getting metadata for " + ldfURL);
                reject(err);
                return;
            }
            //Get the number of triples in the dataset
            if (triple && triple.subject === ldfURL && triple.predicate === 'http://rdfs.org/ns/void#triples') {
                var numTriples = parseInt(N3.Util.getLiteralValue(triple.object));
                var maxPage = Math.ceil(numTriples / 100.);
                var pagesToSample = Math.ceil(numTriples * SAMPLING_FACTOR / 100);
                var pageInterval = maxPage / pagesToSample;

                var remainingPages = pagesToSample;
                var urls = {};

                //Sample uniformly distributed pages of the datasets so we (hopefully) get a representative distribution
                // of the resources being used.
                console.log("Getting " + pagesToSample + " pages from " + ldfURL);
                for (var i = 0; i < pagesToSample; i++) {
                    var pageURL = ldfURL + "?page=" + (1 + i*pageInterval);
                    //console.log(pageURL);
                    streamTriples(pageURL, function(err, triple) {
                        if (err) {
                            console.log("Error getting data page " + ldfURL);
                            reject(err);
                            return;
                        }
                        if (triple) {
                            //Skip LDF metadata
                            if (triple.graph !== '') {
                                return;
                            }
                            [triple.subject, triple.predicate, triple.object].forEach(function(elem) {
                                if (N3.Util.isIRI(elem)) {
                                    var host = urlparse(elem).host;
                                    urls[host] = (urls[host] || 0) + 1;
                                }
                            });
                        } else {
                            remainingPages = remainingPages - 1;
                            console.log("Parsed result page from " + ldfURL + " (" + remainingPages + " remaining).");
                            if (remainingPages == 0) {
                                resolve(urls);
                            }
                        }
                    })
                }
            }
        })
Пример #22
0
reader.addListener('data', function (data) {
  //writer.addTriple(data["URI"], "rdfs:type","gtfs:Station", "http://irail.be/stations/NMBS");
  writer.addTriple(data["URI"], N3Util.expandPrefixedName("foaf:name", prefixes),'"' + data["name"] + '"', "http://irail.be/stations/NMBS");
  if (data["alternative-en"] !== "") {
    writer.addTriple(data["URI"], N3Util.expandPrefixedName("dcterms:alternative", prefixes),'"' + data["alternative-en"] + '"@en', "http://irail.be/stations/NMBS");
  }

  if (data["alternative-fr"] !== "") {
    writer.addTriple(data["URI"], N3Util.expandPrefixedName("dcterms:alternative", prefixes),'"' + data["alternative-fr"] + '"@fr', "http://irail.be/stations/NMBS");
  }
  if (data["alternative-nl"] !== "") {
    writer.addTriple(data["URI"], N3Util.expandPrefixedName("dcterms:alternative", prefixes),'"' + data["alternative-nl"] + '"@nl', "http://irail.be/stations/NMBS");
  }
  if (data["alternative-de"] !== "") {
    writer.addTriple(data["URI"], N3Util.expandPrefixedName("dcterms:alternative", prefixes),'"' + data["alternative-de"] + '"@de', "http://irail.be/stations/NMBS");
  }
  writer.addTriple(data["URI"], N3Util.expandPrefixedName("gn:parentCountry", prefixes), countryURIs[data["country-code"]], "http://irail.be/stations/NMBS");
  writer.addTriple(data["URI"], N3Util.expandPrefixedName("geo:long", prefixes),'"' + data["longitude"] + '"', "http://irail.be/stations/NMBS");
  writer.addTriple(data["URI"], N3Util.expandPrefixedName("geo:lat", prefixes),'"' + data["latitude"] + '"', "http://irail.be/stations/NMBS");
  writer.addTriple(data["URI"], N3Util.expandPrefixedName("st:avgStopTimes",prefixes),'"' + data["avg_stop_times"] + '"', "http://irail.be/stations/NMBS");
});
Пример #23
0
test('N3 Utils', async t => {
  const prefixes = N3.Util.prefixes({
    ex: 'http://example.com/',
  })

  const { store } = await rdfToStore(`
    @prefix ex: <http://example.com/> .

    ex:a ex:b ex:c .

    ex:list ex:members (
      ex:d
      ex:e
      ex:f
    ) .
  `)

  t.equal(store.size, 8, 'should parse an RDF string into an N3 Store')

  t.deepEqual(
    await findOne(store, prefixes('ex')('a')),
    N3.DataFactory.quad(
      namedNode('http://example.com/a'),
      namedNode('http://example.com/b'),
      namedNode('http://example.com/c'),
    ),
    'should be able to find one triple in a store'
  )

  const listHeadNode = (await findOne(
    store,
    prefixes('ex')('list'),
    prefixes('ex')('members'),
  )).object

  t.deepEqual(
    await rdfListToArray(store, listHeadNode),
    [
      namedNode('http://example.com/d'),
      namedNode('http://example.com/e'),
      namedNode('http://example.com/f'),
    ],
    'should convert RDF lists to JS arrays'
  )
})
Пример #24
0
function nsExpander(prefixes) {
  const n3fn = N3.Util.prefixes(prefixes)

  function expandNS(arg) {
    const colonPos = arg.indexOf(':')

    return colonPos > -1
      ? n3fn(arg.slice(0, colonPos))(arg.slice(colonPos + 1))
      : n3fn(arg)
  }

  return Object.assign(expandNS, {
    prefixes,
    withPrefixes(extra) {
      return nsExpander(Object.assign({}, prefixes, extra))
    }
  })
}
 return function (bindings) {
   // Evaluate the arguments
   var args = new Array(argumentExpressions.length);
   for (var i = 0; i < argumentExpressions.length; i++) {
     var arg = args[i] = argumentExpressions[i](bindings);
     // Convert the arguments if necessary
     switch (operator.type) {
       case 'numeric':
         isFinite(arg) || (args[i] = parseFloat(N3Util.getLiteralValue(arg)));
         break;
       case 'boolean':
         if (arg !== false && arg !== true)
           throw new Error(operatorName + ' needs a boolean but got: ' + arg + '.');
         break;
     }
   }
   // Call the operator on the evaluated arguments
   return operator.apply(null, args);
 };
Пример #26
0
 function createTerm (termString) {
   var value
   if (N3.Util.isLiteral(termString)) {
     value = N3.Util.getLiteralValue(termString)
     var language = N3.Util.getLiteralLanguage(termString)
     var datatype = new NamedNode(N3.Util.getLiteralType(termString))
     return new Literal(value, language, datatype)
   } else if (N3.Util.isIRI(termString)) {
     return new NamedNode(termString)
   } else if (N3.Util.isBlank(termString)) {
     value = termString.substring(2, termString.length)
     return new BlankNode(value)
   } else {
     return null
   }
 }
  function (request, query, datasourceSettings) {
  // TODO: these URLs should be generated by the routers
  var requestUrl = _.assign(url.parse(request.url, true),
                            { protocol: 'http', host: request.headers.host }),
      requestQuery = requestUrl.query,
      currentPage = parseInt(requestQuery.page, 10) || 1,
      datasourceUrl = url.format(_.omit(requestUrl, 'search', 'query')),
      fragmentUrl = url.format(_.defaults({ search: '', query: _.omit(requestQuery, 'page'), },
                               requestUrl)),
      fragmentPageUrlBase = fragmentUrl + (/\?/.test(fragmentUrl) ? '&' : '?') + 'page=',
      indexUrl = url.format(_.omit(requestUrl, 'search', 'query', 'pathname')) + '/';

  // Generate a textual representation of the pattern
  query.patternString = '{ ' +
    (query.subject              ? '<' + query.subject   + '> ' : '?s ') +
    (query.predicate            ? '<' + query.predicate + '> ' : '?p ') +
    (N3Util.isIRI(query.object) ? '<' + query.object    + '> ' : '?o ') +
    (datasourceSettings.datasource.isQuadsEnabled ? (query.context ? '<' + query.context + '> ' : '?g ') : '') + '}';

  return {
    datasource: _.assign(_.omit(datasourceSettings, 'datasource'), {
      index: indexUrl + '#dataset',
      url: datasourceUrl + '#dataset',
      templateUrl: datasourceUrl + '{?subject,predicate,object' +
                   (datasourceSettings.datasource.isQuadsEnabled ? ',context' : '') + '}',
      isQuadsEnabled: datasourceSettings.datasource.isQuadsEnabled ? true : false,
    }),
    fragment: {
      url: fragmentUrl,
      pageUrl: url.format(requestUrl),
      firstPageUrl: fragmentPageUrlBase + '1',
      nextPageUrl: fragmentPageUrlBase + (currentPage + 1),
      previousPageUrl: currentPage > 1 ? fragmentPageUrlBase + (currentPage - 1) : null,
    },
    query: query,
    prefixes: this._prefixes,
    datasources: this._datasources,
  };
};
 str: function (a) {
   return N3Util.isLiteral(a) ? a : '"' + a + '"';
 },
 regex: function (subject, pattern) {
   if (N3Util.isLiteral(subject))
     subject = N3Util.getLiteralValue(subject);
   return new RegExp(N3Util.getLiteralValue(pattern)).test(subject);
 },
 lang: function (a)    {
   return '"' + N3Util.getLiteralLanguage(a).toLowerCase() + '"';
 },