Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F60114543
query.service.ts
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Sat, Apr 27, 14:56
Size
8 KB
Mime Type
text/x-java
Expires
Mon, Apr 29, 14:56 (2 d)
Engine
blob
Format
Raw Data
Handle
17303193
Attached To
rNIETZSCHEBETAAPP Nietzsche-Beta-App
query.service.ts
View Options
import { Injectable } from '@angular/core';
import { Parser, Generator, Wildcard } from 'sparqljs';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {DELETE_LIST_ENTRIES_RQ, DELETE_SPO_RQ} from '../rdf-editor-module/constants';
@Injectable()
export class QueryService {
constructor(private http: HttpClient) {
}
/**
* Gets the data from an endpoint via http post
*
* @param baseUrl: The url of the endpoint.
* @param query: The query to run.
* @param queryType: "CONSTRUCT" or "QUERY"
* @returns the response.
*/
public getData(baseUrl: string, query: string, queryType?: string ) {
let httpOptions;
if (queryType === 'CONSTRUCT') {
// A construct does contain a text as response, not a json, so responseType must be 'text' to avoid parse errors
httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/sparql-query', 'Accept': 'text/turtle'}),
responseType: 'text'};
return this.http.post(baseUrl, query, httpOptions).toPromise();
} if (queryType === 'SELECT' || queryType === 'ASK') {
httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/sparql-query',
'Accept': 'application/sparql-results+json; charset=UTF-8'})};
return this.http.post(baseUrl, query, httpOptions).toPromise();
}
}
public updateData(baseUrl: string, data: string) {
let query = `INSERT DATA {${data}}`;
let httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/sparql-update',
'Authorization': 'Basic bmlldHpzY2hlX3VzZXI6bmlldHpzY2hl',
'Accept': 'application/sparql-results+json; charset=UTF-8'}), method: 'POST', body: query};
this.http.post(baseUrl, query, httpOptions).toPromise().then(fuu => console.log(fuu) );
}
/**
* Gets a text file by its name from the directory assets/queries.
*
* @param filename The name of the file + file name extension.
* @returns the text of the file.
*/
public getQueryfromFilename(filename) {
return this.http.get('../assets/queries/' + filename, {responseType: 'text'}).toPromise();
}
/**
* parametrizeSimpleQueryWithItem()
* Parametrizes a given baseQuery's where clause with an iri passed. only the first where clause will be parametrized
*
* @param subjectIri: The iri of the selected resource
* @param baseQuery: name of the query to parametrize
* @param propertyIri: The iri of the selected property
* @param objectIri: The iri of the selected object
* @returns the query for the resource.
*/
public parametrizeWhereClauseWithItems(baseQuery: string, subjectIri?: string, predicateIri?: string, objectIri?: string): string {
let qParametrizer = new TlnQueryParametrizer(baseQuery);
qParametrizer.parametrizeWhereSPO(subjectIri, predicateIri, objectIri);
return qParametrizer.writeOut();
}
// the static version
public static parametrizeWhereClauseWithItem(baseQuery: string, subjectIri?: string, propertyIri?: string, objectIri?: string): string {
let qParametrizer = new TlnQueryParametrizer(baseQuery);
qParametrizer.parametrizeWhereSPO(subjectIri, propertyIri, objectIri);
return qParametrizer.writeOut();
}
// binds an iri to a variable and adds the BIND on top of the Where clause
public bindVariableWithIri(baseQuery: string, variable: string, iri: string) {
let qParametrizer = new TlnQueryParametrizer(baseQuery);
qParametrizer.bindVariable(variable, iri);
return qParametrizer.writeOut();
}
// binds an iri to a variable and adds the BIND on top of the Where clause
public static bindVariableWithIri(baseQuery: string, variable: string, iri: string, type = 0) {
let qParametrizer = new TlnQueryParametrizer(baseQuery);
qParametrizer.bindVariable(variable, iri, type);
return qParametrizer.writeOut();
}
}
export class TlnQueryParametrizer {
parsedQuery;
parser: Parser;
sparqlGenerator = new Generator({});
constructor(baseQuery: string) {
this.parser = new Parser();
this.parsedQuery = this.parser.parse(baseQuery);
}
// parametrizes the first occurence of a given s p o in the first where clause
parametrizeWhereSPO(subjectIri?: string, predicateIri?: string, objectIri?: string) {
// get the idx of the first where clause
this.setNode(subjectIri, 'subject');
this.setNode(predicateIri, 'predicate');
this.setNode(objectIri, 'object');
}
setNode(iri: string, role: string): void {
if (!iri || iri === '') { return } // guard
if (this.parsedQuery.type === 'update') {
this.parsedQuery.updates[0].where[0].triples[0][role] = {'termType': 'NamedNode', 'value': decodeURI(iri) };
} else {
const whereIdx = this.parsedQuery.where.findIndex(where => where.type === 'bgp');
// console.log(this.parsedQuery.where[whereIdx].triples[0][role])
this.parsedQuery.where[whereIdx].triples[0][role] = {'termType': 'NamedNode', 'value': decodeURI(iri) };
if (this.parsedQuery.queryType === 'CONSTRUCT') { // in case of constructs we also change the template subject
this.parsedQuery.template[0][role] = {'termType': 'NamedNode', 'value': decodeURI(iri) };
}
}
}
setSubject(subjectIri: string, whereIdx): void {
if (!subjectIri || subjectIri === '') { return } // guard
this.parsedQuery.where[whereIdx].triples[0].subject = {'termType': 'NamedNode', 'value': decodeURI(subjectIri) };
if (this.parsedQuery.queryType === 'CONSTRUCT') { // in case of constructs we also change the template subject
this.parsedQuery.template[0].subject = {'termType': 'NamedNode', 'value': decodeURI(subjectIri) };
}
}
setPredicate(predicateIri: string, whereIdx): void { //guard
if (!predicateIri || predicateIri === '') { return }
this.parsedQuery.where[whereIdx].triples[0].predicate = {'termType': 'NamedNode', 'value': decodeURI(predicateIri) };
if (this.parsedQuery.queryType === 'CONSTRUCT') { // in case of constructs we also change the template perdicate
this.parsedQuery.template[0].predicate = {'termType': 'NamedNode', 'value': decodeURI(predicateIri) };
}
}
setObject(objectIri: string, whereIdx): void {
if (!objectIri || objectIri === '') { return } // guard
this.parsedQuery.where[whereIdx].triples[0].object = {'termType': 'NamedNode', 'value': decodeURI(objectIri) };
if (this.parsedQuery.queryType === 'CONSTRUCT') { // in case of constructs we also change the template object
this.parsedQuery.template[0].object = {'termType': 'NamedNode', 'value': decodeURI(objectIri) };
}
}
bindVariable(variable: string, iri: string, type: number = 0) {
let bind = {
expression: {
termType: "Uri",
value: iri,
language: "",
datatype: {termType: "NamedNode", value:"http://www.w3.org/2001/XMLSchema#string" }
},
type: "bind",
variable: {termType: 'Variable', value: variable} }
if (type === 0) { // select query
this.parsedQuery.where.splice(0, 0, bind );
}
if (type === 1) { //updatedelete
// console.log(type, variable, iri);
this.parsedQuery.updates[0].where.splice(0, 0, bind );
}
}
// sets all occurencies of a variable
setVars(node: string, value: string) {
let bgp = this.parsedQuery.where.filter(where => where.type === 'bgp');
if (bgp.length <= 1 || !bgp.triples || bgp.triples.length <= 1) { return} // guard
const valueNode = {'termType': 'NamedNode', 'value': decodeURI(value)};
let variableToParametrize = bgp.triples[0][node].value;
// replacing all occurenceis of variableToParametrize in the where clause
for (let i = 0; i <= this.parsedQuery.where.length; i++) {
if (this.parsedQuery.where[i].triples[0].subject.value === variableToParametrize) {
this.parsedQuery.where[i].triples[0].subject = valueNode; }
if (this.parsedQuery.where[i].triples[0].predicate.value === variableToParametrize) {
this.parsedQuery.where[i].triples[0].predicate = valueNode }
if (this.parsedQuery.where[i].triples[0].object.value === variableToParametrize) {
this.parsedQuery.where[i].triples[0].object = valueNode }
}
}
// Deletes all list entries & all lists of a subject for a given predicate
public static getDelQueriesOfListsOfSP(subjectIri: string, predicateIri: string): string[] {
// parametrize first the subject
const qSubject = QueryService.bindVariableWithIri(DELETE_LIST_ENTRIES_RQ, 'mySubject', subjectIri, 1);
// then the predicate
const delListEntriesQuery = QueryService.bindVariableWithIri(qSubject, 'myPredicate', predicateIri, 1);
console.log('delListEntriesQuery', delListEntriesQuery)
// parametrize the query to delete the triples
const delSPOToList = QueryService.parametrizeWhereClauseWithItem(DELETE_SPO_RQ, subjectIri, predicateIri) ;
return [delListEntriesQuery, delSPOToList];
}
writeOut() {
return this.sparqlGenerator.stringify(this.parsedQuery);
}
}
Event Timeline
Log In to Comment