/// <summary> /// Creates a new Query Handler Configuration /// </summary> /// <param name="context">HTTP Context</param> /// <param name="g">Configuration Graph</param> /// <param name="objNode">Object Node</param> public BaseQueryHandlerConfiguration(IHttpContext context, IGraph g, INode objNode) : base(context, g, objNode) { // Get the Query Processor to be used ISparqlQueryProcessor processor; INode procNode = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyQueryProcessor))); if (procNode == null) { throw new DotNetRdfConfigurationException("Unable to load Query Handler Configuration as the RDF configuration file does not specify a dnr:queryProcessor property for the Handler"); } Object temp = ConfigurationLoader.LoadObject(g, procNode); if (temp is ISparqlQueryProcessor) { processor = (ISparqlQueryProcessor)temp; } else { throw new DotNetRdfConfigurationException("Unable to load Query Handler Configuration as the RDF configuration file specifies a value for the Handlers dnr:updateProcessor property which cannot be loaded as an object which implements the ISparqlQueryProcessor interface"); } this._processor = processor; // SPARQL Query Default Config this._defaultGraph = ConfigurationLoader.GetConfigurationValue(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyDefaultGraphUri)))?.ToString() ?? string.Empty; this._defaultTimeout = ConfigurationLoader.GetConfigurationInt64(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyTimeout)), this._defaultTimeout); this._defaultPartialResults = ConfigurationLoader.GetConfigurationBoolean(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyPartialResults)), this._defaultPartialResults); // Handler Configuration this._showQueryForm = ConfigurationLoader.GetConfigurationBoolean(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyShowQueryForm)), this._showQueryForm); String defQueryFile = ConfigurationLoader.GetConfigurationString(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyDefaultQueryFile))); if (defQueryFile != null) { defQueryFile = ConfigurationLoader.ResolvePath(defQueryFile); if (File.Exists(defQueryFile)) { using (StreamReader reader = new StreamReader(defQueryFile)) { this._defaultQuery = reader.ReadToEnd(); reader.Close(); } } } // Get Query Syntax to use try { String syntaxSetting = ConfigurationLoader.GetConfigurationString(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertySyntax))); if (syntaxSetting != null) { this._syntax = (SparqlQuerySyntax)Enum.Parse(typeof(SparqlQuerySyntax), syntaxSetting); } } catch (Exception ex) { throw new DotNetRdfConfigurationException("Unable to set the Syntax for the HTTP Handler identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:syntax property was not a valid value from the enum VDS.RDF.Parsing.SparqlQuerySyntax", ex); } // Get the SPARQL Describe Algorithm INode describeNode = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyDescribeAlgorithm))); if (describeNode != null) { if (describeNode.NodeType == NodeType.Literal) { String algoClass = ((ILiteralNode)describeNode).Value; try { Object desc = Activator.CreateInstance(Type.GetType(algoClass)); if (desc is ISparqlDescribe) { this._describer = (ISparqlDescribe)desc; } else { throw new DotNetRdfConfigurationException("Unable to set the Describe Algorithm for the HTTP Handler identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:describeAlgorithm property was not a type name of a type that implements the ISparqlDescribe interface"); } } catch (DotNetRdfConfigurationException) { throw; } catch (Exception ex) { throw new DotNetRdfConfigurationException("Unable to set the Describe Algorithm for the HTTP Handler identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:describeAlgorithm property was not a type name for a type that can be instantiated", ex); } } } // Get the Service Description Graph INode descripNode = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyServiceDescription))); if (descripNode != null) { Object descrip = ConfigurationLoader.LoadObject(g, descripNode); if (descrip is IGraph) { this._serviceDescription = (IGraph)descrip; } else { throw new DotNetRdfConfigurationException("Unable to set the Service Description Graph for the HTTP Handler identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:serviceDescription property points to an Object which could not be loaded as an object which implements the required IGraph interface"); } } // Get the Query Optimiser INode queryOptNode = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyQueryOptimiser))); if (queryOptNode != null) { Object queryOpt = ConfigurationLoader.LoadObject(g, queryOptNode); if (queryOpt is IQueryOptimiser) { this._queryOptimiser = (IQueryOptimiser)queryOpt; } else { throw new DotNetRdfConfigurationException("Unable to set the Query Optimiser for the HTTP Handler identified by the Node '" + queryOptNode.ToString() + "' as the value given for the dnr:queryOptimiser property points to an Object which could not be loaded as an object which implements the required IQueryOptimiser interface"); } } // Get the Algebra Optimisers foreach (INode algOptNode in ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyAlgebraOptimiser)))) { Object algOpt = ConfigurationLoader.LoadObject(g, algOptNode); if (algOpt is IAlgebraOptimiser) { this._algebraOptimisers.Add((IAlgebraOptimiser)algOpt); } else { throw new DotNetRdfConfigurationException("Unable to set the Algebra Optimiser for the HTTP Handler identified by the Node '" + algOptNode.ToString() + "' as the value given for the dnr:algebraOptimiser property points to an Object which could not be loaded as an object which implements the required IAlgebraOptimiser interface"); } } }
/// <summary> /// Creates a new double valued node. /// </summary> /// <param name="g">Graph the node belongs to.</param> /// <param name="value">Double value.</param> /// <param name="lexicalValue">Lexical value.</param> public DoubleNode(IGraph g, double value, String lexicalValue) : base(g, lexicalValue, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeDouble), SparqlNumericType.Double) { _value = value; }
/// <summary> /// Tries to load a Web Proxy based on information from the Configuration Graph. /// </summary> /// <param name="g">Configuration Graph.</param> /// <param name="objNode">Object Node.</param> /// <param name="targetType">Target Type.</param> /// <param name="obj">Output Object.</param> /// <returns></returns> public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj) { obj = null; WebProxy proxy = null; // Can we create a Proxy? String server = ConfigurationLoader.GetConfigurationString(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyServer))); if (server == null) { return(false); } proxy = new WebProxy(server); // Does the proxy have credentials attached? String user, pwd; ConfigurationLoader.GetUsernameAndPassword(g, objNode, true, out user, out pwd); if (user != null && pwd != null) { proxy.Credentials = new NetworkCredential(user, pwd); } obj = proxy; return(proxy != null); }
public void StorageVirtuosoBlankNodeInsert() { VirtuosoManager manager = VirtuosoTest.GetConnection(); try { Graph g = new Graph(); Triple t = new Triple(g.CreateBlankNode(), g.CreateUriNode("rdf:type"), g.CreateUriNode(UriFactory.Create("http://example.org/object"))); manager.UpdateGraph("http://localhost/insertBNodeTest", t.AsEnumerable(), null); Object results = manager.Query("ASK WHERE { GRAPH <http://localhost/insertBNodeTest> { ?s a <http:///example.org/object> } }"); if (results is SparqlResultSet) { TestTools.ShowResults(results); Assert.IsTrue(((SparqlResultSet)results).Result, "Expected a true result"); } else { Assert.Fail("Didn't get a SPARQL Result Set as expected"); } } finally { if (manager != null) { manager.Dispose(); } } }
/// <summary> /// Returns the value of the Expression as evaluated for a given Binding as a Literal Node /// </summary> /// <param name="context">Evaluation Context</param> /// <param name="bindingID">Binding ID</param> /// <returns></returns> public IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID) { ILiteralNode input = (ILiteralNode)this.CheckArgument(this._expr, context, bindingID); IValuedNode start = this.CheckArgument(this._start, context, bindingID, XPathFunctionFactory.AcceptNumericArguments); if (this._length != null) { IValuedNode length = this.CheckArgument(this._length, context, bindingID, XPathFunctionFactory.AcceptNumericArguments); if (input.Value.Equals(string.Empty)) { return(new StringNode(null, string.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } int s = Convert.ToInt32(start.AsInteger()); int l = Convert.ToInt32(length.AsInteger()); if (s < 1) { s = 1; } if (l < 1) { //If no/negative characters are being selected the empty string is returned return(new StringNode(null, string.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else if ((s - 1) > input.Value.Length) { //If the start is after the end of the string the empty string is returned return(new StringNode(null, string.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else { if (((s - 1) + l) > input.Value.Length) { //If the start plus the length is greater than the length of the string the string from the starts onwards is returned return(new StringNode(null, input.Value.Substring(s - 1), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else { //Otherwise do normal substring return(new StringNode(null, input.Value.Substring(s - 1, l), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } } } else { if (input.Value.Equals(string.Empty)) { return(new StringNode(null, string.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } int s = Convert.ToInt32(start.AsInteger()); if (s < 1) { s = 1; } return(new StringNode(null, input.Value.Substring(s - 1), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } }
/// <summary> /// Creates a new Serialization Context. /// </summary> public ConfigurationSerializationContext() { _g = new Graph(); _g.NamespaceMap.AddNamespace("dnr", UriFactory.Create(ConfigurationLoader.ConfigurationNamespace)); }
public void SparqlUpdateDeleteWithGraphClause2() { Graph g = new Graph(); g.Assert(g.CreateUriNode(UriFactory.Create("http://subject")), g.CreateUriNode(UriFactory.Create("http://predicate")), g.CreateUriNode(UriFactory.Create("http://object"))); Graph h = new Graph(); h.Merge(g); h.BaseUri = UriFactory.Create("http://subject"); InMemoryDataset dataset = new InMemoryDataset(g); dataset.AddGraph(h); dataset.Flush(); Assert.Equal(2, dataset.GraphUris.Count()); String updates = "DELETE { GRAPH ?s { ?s ?p ?o } } INSERT { GRAPH ?o { ?s ?p ?o } } WHERE { ?s ?p ?o }"; SparqlUpdateCommandSet commands = new SparqlUpdateParser().ParseFromString(updates); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); processor.ProcessCommandSet(commands); Assert.Equal(3, dataset.GraphUris.Count()); Assert.True(dataset.HasGraph(UriFactory.Create("http://subject"))); Assert.True(dataset.HasGraph(UriFactory.Create("http://object"))); Assert.Equal(0, dataset[UriFactory.Create("http://subject")].Triples.Count); }
private void TryParseTriple(XmlNode tripleEl, IRdfHandler handler, Uri graphUri) { //Verify Node Name if (!tripleEl.Name.Equals("triple")) { throw new RdfParseException("Unexpected Element <" + tripleEl.Name + "> encountered, only an optional <uri> element followed by zero/more <triple> elements are permitted within a <graph> element"); } //Verify number of Child Nodes if (!tripleEl.HasChildNodes) { throw new RdfParseException("<triple> element has no child nodes - 3 child nodes are expected"); } if (tripleEl.ChildNodes.Count < 3) { throw new RdfParseException("<triple> element has too few child nodes (" + tripleEl.ChildNodes.Count + ") - 3 child nodes are expected"); } if (tripleEl.ChildNodes.Count > 3) { throw new RdfParseException("<triple> element has too many child nodes (" + tripleEl.ChildNodes.Count + ") - 3 child nodes are expected"); } //Get the 3 Child Nodes XmlNode subjEl, predEl, objEl; subjEl = tripleEl.ChildNodes[0]; predEl = tripleEl.ChildNodes[1]; objEl = tripleEl.ChildNodes[2]; //Parse XML Nodes into RDF Nodes INode subj, pred, obj; if (subjEl.Name.Equals("uri")) { subj = handler.CreateUriNode(UriFactory.Create(subjEl.InnerText)); } else if (subjEl.Name.Equals("id")) { subj = handler.CreateBlankNode(subjEl.InnerText); } else { throw Error("Unexpected element <" + subjEl.Name + "> encountered, expected a <id>/<uri> element as the Subject of a Triple", subjEl); } if (predEl.Name.Equals("uri")) { pred = handler.CreateUriNode(UriFactory.Create(predEl.InnerText)); } else { throw Error("Unexpected element <" + predEl.Name + "> encountered, expected a <uri> element as the Predicate of a Triple", subjEl); } if (objEl.Name.Equals("uri")) { obj = handler.CreateUriNode(UriFactory.Create(objEl.InnerText)); } else if (objEl.Name.Equals("id")) { obj = handler.CreateBlankNode(objEl.InnerText); } else if (objEl.Name.Equals("plainLiteral")) { if (objEl.Attributes.GetNamedItem("xml:lang") != null) { obj = handler.CreateLiteralNode(objEl.InnerText, objEl.Attributes["xml:lang"].Value); } else { obj = handler.CreateLiteralNode(objEl.InnerText); } } else if (objEl.Name.Equals("typedLiteral")) { if (objEl.Attributes.GetNamedItem("datatype") != null) { Uri dtUri = UriFactory.Create(objEl.Attributes["datatype"].Value); if (objEl.FirstChild.NodeType == XmlNodeType.Text) { obj = handler.CreateLiteralNode(objEl.InnerText, dtUri); } else if (objEl.FirstChild.NodeType == XmlNodeType.CDATA) { obj = handler.CreateLiteralNode(objEl.FirstChild.InnerXml, dtUri); } else { obj = handler.CreateLiteralNode(objEl.InnerText, dtUri); } } else { throw Error("<typedLiteral> element does not have the required datatype attribute", objEl); } } else { throw Error("Unexpected element <" + objEl.Name + "> encountered, expected a <id>/<uri>/<plainLiteral>/<typedLiteral> element as the Object of a Triple", subjEl); } //Assert the resulting Triple if (!handler.HandleTriple(new Triple(subj, pred, obj, graphUri))) { ParserHelper.Stop(); } ; }
/// <summary> /// Serializes the connection's configuration /// </summary> /// <param name="context">Configuration Serialization Context</param> public void SerializeConfiguration(ConfigurationSerializationContext context) { INode manager = context.NextSubject; INode rdfType = context.Graph.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType)); INode rdfsLabel = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "label")); INode dnrType = ConfigurationLoader.CreateConfigurationNode(context.Graph, ConfigurationLoader.PropertyType); INode genericManager = ConfigurationLoader.CreateConfigurationNode(context.Graph, ConfigurationLoader.ClassGenericManager); context.Graph.Assert(new Triple(manager, rdfType, genericManager)); context.Graph.Assert(new Triple(manager, rdfsLabel, context.Graph.CreateLiteralNode(this.ToString()))); context.Graph.Assert(new Triple(manager, dnrType, context.Graph.CreateLiteralNode(this.GetType().FullName))); //TODO: Serialize Load Mode here if (this._endpoint is IConfigurationSerializable) { //Use the indirect serialization method //Serialize the Endpoints Configuration INode endpoint = ConfigurationLoader.CreateConfigurationNode(context.Graph, ConfigurationLoader.PropertyEndpoint); INode endpointObj = context.Graph.CreateBlankNode(); context.NextSubject = endpointObj; ((IConfigurationSerializable)this._endpoint).SerializeConfiguration(context); //Link that serialization to our serialization context.Graph.Assert(new Triple(manager, endpoint, endpointObj)); } else { //Use the direct serialization method INode endpointUri = ConfigurationLoader.CreateConfigurationNode(context.Graph, ConfigurationLoader.PropertyEndpointUri); INode defGraphUri = ConfigurationLoader.CreateConfigurationNode(context.Graph, ConfigurationLoader.PropertyDefaultGraphUri); INode namedGraphUri = ConfigurationLoader.CreateConfigurationNode(context.Graph, ConfigurationLoader.PropertyNamedGraphUri); context.Graph.Assert(new Triple(manager, endpointUri, context.Graph.CreateLiteralNode(this._endpoint.Uri.ToString()))); foreach (String u in this._endpoint.DefaultGraphs) { context.Graph.Assert(new Triple(manager, defGraphUri, context.Graph.CreateUriNode(UriFactory.Create(u)))); } foreach (String u in this._endpoint.NamedGraphs) { context.Graph.Assert(new Triple(manager, namedGraphUri, context.Graph.CreateUriNode(UriFactory.Create(u)))); } } }
/// <summary> /// Gets the Value of the function as applied to the given String Literal /// </summary> /// <param name="stringLit">Simple/String typed Literal</param> /// <returns></returns> protected override IValuedNode ValueInternal(ILiteralNode stringLit) { return(new StringNode(null, stringLit.Value.ToLower(), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); }
private void TryParseGraph(XmlNode graphEl, IRdfHandler handler) { //Ensure Node Name is correct if (!graphEl.Name.Equals("graph")) { throw new RdfParseException("Unexpected Element <" + graphEl.Name + "> encountered, only <graph> elements are permitted within a <TriX> element"); } if (graphEl.HasChildNodes) { //Check whether this Graph is actually asserted if (graphEl.Attributes.GetNamedItem("asserted") != null) { bool asserted = true; if (Boolean.TryParse(graphEl.Attributes["asserted"].Value, out asserted)) { //Don't process this Graph further if it is not being asserted //i.e. it is only (potentially) being quoted if (!asserted) { this.RaiseWarning("A Graph is marked as not asserted in the TriX input. This Graph will not be parsed, if you reserialize the input the information contained in it will not be preserved"); return; } } } //See if we get an <id>/<uri> node to name the Graph bool skipFirst = true; XmlNode nameEl = graphEl.FirstChild; //Watch out for Comments and other non-Element nodes if (nameEl.NodeType != XmlNodeType.Element) { foreach (XmlNode n in graphEl.ChildNodes) { if (n.NodeType == XmlNodeType.Element) { nameEl = n; break; } } } //Process the name into a Graph Uri and create the Graph and add it to the Store Uri graphUri; if (nameEl.Name.Equals("uri")) { //TODO: Add support for reading Base Uri from xml:base attributes in the file graphUri = UriFactory.Create(Tools.ResolveUri(nameEl.InnerText, String.Empty)); } else { skipFirst = false; graphUri = null; } //Process the Child Nodes of the <graph> element to yield Triples foreach (XmlNode triple in graphEl.ChildNodes) { //Remember to ignore anything that isn't an element i.e. comments and processing instructions if (triple.NodeType == XmlNodeType.Element) { if (skipFirst) { skipFirst = false; continue; } this.TryParseTriple(triple, handler, graphUri); } } } }
/// <summary> /// Deletes a Graph from the Store /// </summary> /// <param name="graphUri">URI of the Graph to delete</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public void DeleteGraph(string graphUri, AsyncStorageCallback callback, object state) { Uri u = (String.IsNullOrEmpty(graphUri) ? null : UriFactory.Create(graphUri)); this.DeleteGraph(u, callback, state); }
/// <summary> /// Updates a Graph in the Store asychronously /// </summary> /// <param name="graphUri">URI of the Graph to update</param> /// <param name="additions">Triples to be added</param> /// <param name="removals">Triples to be removed</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public void UpdateGraph(string graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals, AsyncStorageCallback callback, object state) { Uri u = (String.IsNullOrEmpty(graphUri) ? null : UriFactory.Create(graphUri)); this.UpdateGraph(u, additions, removals, callback, state); }
/// <summary> /// Loads a Graph from the Store asynchronously /// </summary> /// <param name="handler">Handler to load with</param> /// <param name="graphUri">URI of the Graph to load</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> public void LoadGraph(IRdfHandler handler, string graphUri, AsyncStorageCallback callback, object state) { Uri u = (String.IsNullOrEmpty(graphUri) ? null : UriFactory.Create(graphUri)); this.LoadGraph(handler, u, callback, state); }
/// <summary> /// Removes all sub-classes for this class. /// </summary> /// <returns></returns> public bool ClearSubClasses() { _graph.Retract(_graph.GetTriplesWithPredicateObject(_graph.CreateUriNode(UriFactory.Create(OntologyHelper.PropertySubClassOf)), _resource).ToList()); return(ClearResourceProperty(PropertyDerivedClass, false)); }
/// <summary> /// Returns the value of the Expression as evaluated for a given Binding as a Literal Node. /// </summary> /// <param name="context">Evaluation Context.</param> /// <param name="bindingID">Binding ID.</param> /// <returns></returns> public IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID) { // Configure Options if (_optionExpr != null) { ConfigureOptions(_optionExpr.Evaluate(context, bindingID), true); } // Compile the Regex if necessary if (!_fixedPattern) { // Regex is not pre-compiled if (_findExpr != null) { IValuedNode p = _findExpr.Evaluate(context, bindingID); if (p != null) { if (p.NodeType == NodeType.Literal) { _find = p.AsString(); } else { throw new RdfQueryException("Cannot parse a Pattern String from a non-Literal Node"); } } else { throw new RdfQueryException("Not a valid Pattern Expression"); } } else { throw new RdfQueryException("Not a valid Pattern Expression or the fixed Pattern String was invalid"); } } // Compute the Replace if necessary if (!_fixedReplace) { if (_replaceExpr != null) { IValuedNode r = _replaceExpr.Evaluate(context, bindingID); if (r != null) { if (r.NodeType == NodeType.Literal) { _replace = r.AsString(); } else { throw new RdfQueryException("Cannot parse a Replace String from a non-Literal Node"); } } else { throw new RdfQueryException("Not a valid Replace Expression"); } } else { throw new RdfQueryException("Not a valid Replace Expression"); } } // Execute the Regular Expression IValuedNode textNode = _textExpr.Evaluate(context, bindingID); if (textNode == null) { throw new RdfQueryException("Cannot evaluate a Regular Expression against a NULL"); } if (textNode.NodeType == NodeType.Literal) { // Execute string text = textNode.AsString(); string output = Regex.Replace(text, _find, _replace, _options); return(new StringNode(null, output, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else { throw new RdfQueryException("Cannot evaluate a Regular Expression against a non-Literal Node"); } }
/// <summary> /// Removes all super-classes. /// </summary> /// <returns></returns> public bool ClearSuperClasses() { _graph.Retract(_graph.GetTriplesWithSubjectPredicate(_resource, _graph.CreateUriNode(UriFactory.Create(OntologyHelper.PropertySubClassOf))).ToList()); return(ClearResourceProperty(OntologyHelper.PropertySubClassOf, true)); }
/// <summary> /// Tries to load a SPARQL Update based on information from the Configuration Graph /// </summary> /// <param name="g">Configuration Graph</param> /// <param name="objNode">Object Node</param> /// <param name="targetType">Target Type</param> /// <param name="obj">Output Object</param> /// <returns></returns> public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj) { obj = null; ISparqlUpdateProcessor processor = null; INode storeObj; Object temp; INode propStorageProvider = g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyStorageProvider)); switch (targetType.FullName) { case LeviathanUpdateProcessor: INode datasetObj = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingDataset))); if (datasetObj != null) { temp = ConfigurationLoader.LoadObject(g, datasetObj); if (temp is ISparqlDataset) { processor = new LeviathanUpdateProcessor((ISparqlDataset)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Leviathan Update Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingDataset property points to an Object that cannot be loaded as an object which implements the ISparqlDataset interface"); } } else { storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingStore))); if (storeObj == null) { return(false); } temp = ConfigurationLoader.LoadObject(g, storeObj); if (temp is IInMemoryQueryableStore) { processor = new LeviathanUpdateProcessor((IInMemoryQueryableStore)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Leviathan Update Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingStore property points to an Object that cannot be loaded as an object which implements the IInMemoryQueryableStore interface"); } } break; case SimpleUpdateProcessor: storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingStore))); if (storeObj == null) { return(false); } temp = ConfigurationLoader.LoadObject(g, storeObj); if (temp is IUpdateableTripleStore) { processor = new SimpleUpdateProcessor((IUpdateableTripleStore)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Simple Update Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingStore property points to an Object that cannot be loaded as an object which implements the IUpdateableTripleStore interface"); } break; case GenericUpdateProcessor: INode managerObj = ConfigurationLoader.GetConfigurationNode(g, objNode, propStorageProvider); if (managerObj == null) { return(false); } temp = ConfigurationLoader.LoadObject(g, managerObj); if (temp is IStorageProvider) { processor = new GenericUpdateProcessor((IStorageProvider)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Generic Update Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:genericManager property points to an Object that cannot be loaded as an object which implements the IStorageProvider interface"); } break; } obj = processor; return(processor != null); }
public void SparqlUpdateInsertWithGraphClause1() { Graph g = new Graph(); g.Assert(g.CreateUriNode(UriFactory.Create("http://subject")), g.CreateUriNode(UriFactory.Create("http://predicate")), g.CreateUriNode(UriFactory.Create("http://object"))); InMemoryDataset dataset = new InMemoryDataset(g); String updates = "INSERT { GRAPH ?s { ?s ?p ?o } } WHERE { ?s ?p ?o }"; SparqlUpdateCommandSet commands = new SparqlUpdateParser().ParseFromString(updates); LeviathanUpdateProcessor processor = new LeviathanUpdateProcessor(dataset); processor.ProcessCommandSet(commands); Assert.Equal(2, dataset.GraphUris.Count()); Assert.True(dataset.HasGraph(UriFactory.Create("http://subject"))); }
/// <summary> /// Tries to load a SPARQL Graph Store HTTP Protocol Processor based on information from the Configuration Graph /// </summary> /// <param name="g">Configuration Graph</param> /// <param name="objNode">Object Node</param> /// <param name="targetType">Target Type</param> /// <param name="obj">Output Object</param> /// <returns></returns> public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj) { obj = null; ISparqlHttpProtocolProcessor processor = null; Object temp; INode propStorageProvider = g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyStorageProvider)); switch (targetType.FullName) { case ProtocolToUpdateProcessor: INode qNode = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyQueryProcessor))); INode uNode = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUpdateProcessor))); if (qNode == null || uNode == null) { return(false); } Object queryProc = ConfigurationLoader.LoadObject(g, qNode); Object updateProc = ConfigurationLoader.LoadObject(g, uNode); if (queryProc is ISparqlQueryProcessor) { if (updateProc is ISparqlUpdateProcessor) { processor = new ProtocolToUpdateProcessor((ISparqlQueryProcessor)queryProc, (ISparqlUpdateProcessor)updateProc); } else { throw new DotNetRdfConfigurationException("Unable to load the SPARQL HTTP Protocol Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:updateProcessor property points to an Object that cannot be loaded as an object which implements the ISparqlUpdateProcessor interface"); } } else { throw new DotNetRdfConfigurationException("Unable to load the SPARQL HTTP Protocol Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:queryProcessor property points to an Object that cannot be loaded as an object which implements the ISparqlQueryProcessor interface"); } break; case LeviathanProtocolProcessor: INode datasetNode = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingDataset))); if (datasetNode != null) { temp = ConfigurationLoader.LoadObject(g, datasetNode); if (temp is ISparqlDataset) { processor = new LeviathanProtocolProcessor((ISparqlDataset)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Leviathan Protocol Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingDataset property points to an Object that cannot be loaded as an object which implements the ISparqlDataset interface"); } } else { INode storeNode = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingStore))); if (storeNode == null) { return(false); } Object store = ConfigurationLoader.LoadObject(g, storeNode); if (store is IInMemoryQueryableStore) { processor = new LeviathanProtocolProcessor((IInMemoryQueryableStore)store); } else { throw new DotNetRdfConfigurationException("Unable to load the SPARQL HTTP Protocol Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingStore property points to an Object that cannot be loaded as an object which implements the IInMemoryQueryableStore interface"); } } break; case GenericProtocolProcessor: INode managerObj = ConfigurationLoader.GetConfigurationNode(g, objNode, propStorageProvider); if (managerObj == null) { return(false); } temp = ConfigurationLoader.LoadObject(g, managerObj); if (temp is IStorageProvider) { processor = new GenericProtocolProcessor((IStorageProvider)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Generic Protocol Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:genericManager property points to an Object that cannot be loaded as an object which implements the IStorageProvider interface"); } break; } obj = processor; return(processor != null); }
public void StorageVirtuosoConfigSerialization() { NTriplesFormatter formatter = new NTriplesFormatter(); VirtuosoManager manager = VirtuosoTest.GetConnection(); try { Assert.IsNotNull(manager); Graph g = new Graph(); INode rdfType = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)); INode dnrType = g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyType)); INode objFactory = g.CreateUriNode(UriFactory.Create(ConfigurationLoader.ClassObjectFactory)); INode virtFactory = g.CreateLiteralNode("VDS.RDF.Configuration.VirtuosoObjectFactory, dotNetRDF.Data.Virtuoso"); INode genericManager = g.CreateUriNode(UriFactory.Create(ConfigurationLoader.ClassStorageProvider)); INode virtManager = g.CreateLiteralNode("VDS.RDF.Storage.VirtuosoManager, dotNetRDF.Data.Virtuoso"); //Serialize Configuration ConfigurationSerializationContext context = new ConfigurationSerializationContext(g); manager.SerializeConfiguration(context); Console.WriteLine("Serialized Configuration"); foreach (Triple t in g.Triples) { Console.WriteLine(t.ToString(formatter)); } Console.WriteLine(); //Ensure that it was serialized INode factory = g.GetTriplesWithPredicateObject(rdfType, objFactory).Select(t => t.Subject).FirstOrDefault(); Assert.IsNotNull(factory, "Should be an object factory in the serialized configuration"); Assert.IsTrue(g.ContainsTriple(new Triple(factory, dnrType, virtFactory)), "Should contain a Triple declaring the dnr:type to be the Virtuoso Object factory type"); INode objNode = g.GetTriplesWithPredicateObject(rdfType, genericManager).Select(t => t.Subject).FirstOrDefault(); Assert.IsNotNull(objNode, "Should be a generic manager in the serialized configuration"); Assert.IsTrue(g.ContainsTriple(new Triple(objNode, dnrType, virtManager)), "Should contain a Triple declaring the dnr:type to be the Virtuoso Manager type"); //Serialize again manager.SerializeConfiguration(context); Console.WriteLine("Serialized Configuration (after 2nd pass)"); foreach (Triple t in g.Triples) { Console.WriteLine(t.ToString(formatter)); } Console.WriteLine(); //Ensure that object factory has not been serialized again Assert.AreEqual(1, g.GetTriplesWithPredicateObject(rdfType, objFactory).Count(), "Should only be 1 Object Factory registered even after a 2nd serializer pass"); //Now try to load the object ConfigurationLoader.AutoConfigureObjectFactories(g); Object loadedObj = ConfigurationLoader.LoadObject(g, objNode); if (loadedObj is VirtuosoManager) { Assert.AreEqual(manager.ToString(), loadedObj.ToString(), "String forms should be equal"); } else { Assert.Fail("Returned an object of type '" + loadedObj.GetType().FullName + "' when deserializing"); } } finally { if (manager != null) { manager.Dispose(); } } }
/// <summary> /// Tries to load a SPARQL Query Processor based on information from the Configuration Graph /// </summary> /// <param name="g">Configuration Graph</param> /// <param name="objNode">Object Node</param> /// <param name="targetType">Target Type</param> /// <param name="obj">Output Object</param> /// <returns></returns> public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj) { obj = null; ISparqlQueryProcessor processor = null; INode storeObj; Object temp; INode propStorageProvider = g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyStorageProvider)); switch (targetType.FullName) { case LeviathanQueryProcessor: INode datasetObj = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingDataset))); if (datasetObj != null) { temp = ConfigurationLoader.LoadObject(g, datasetObj); if (temp is ISparqlDataset) { processor = new LeviathanQueryProcessor((ISparqlDataset)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Leviathan Query Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingDataset property points to an Object that cannot be loaded as an object which implements the ISparqlDataset interface"); } } else { // If no dnr:usingDataset try dnr:usingStore instead storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingStore))); if (storeObj == null) { return(false); } temp = ConfigurationLoader.LoadObject(g, storeObj); if (temp is IInMemoryQueryableStore) { processor = new LeviathanQueryProcessor((IInMemoryQueryableStore)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Leviathan Query Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingStore property points to an Object that cannot be loaded as an object which implements the IInMemoryQueryableStore interface"); } } break; case SimpleQueryProcessor: storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingStore))); if (storeObj == null) { return(false); } temp = ConfigurationLoader.LoadObject(g, storeObj); if (temp is INativelyQueryableStore) { processor = new SimpleQueryProcessor((INativelyQueryableStore)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Simple Query Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingStore property points to an Object that cannot be loaded as an object which implements the INativelyQueryableStore interface"); } break; case GenericQueryProcessor: INode managerObj = ConfigurationLoader.GetConfigurationNode(g, objNode, propStorageProvider); if (managerObj == null) { return(false); } temp = ConfigurationLoader.LoadObject(g, managerObj); if (temp is IQueryableStorage) { processor = new GenericQueryProcessor((IQueryableStorage)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Generic Query Processor identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:genericManager property points to an Object that cannot be loaded as an object which implements the IQueryableStorage interface"); } break; case RemoteQueryProcessor: INode endpointObj = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyEndpoint))); if (endpointObj == null) { return(false); } temp = ConfigurationLoader.LoadObject(g, endpointObj); if (temp is SparqlRemoteEndpoint) { processor = new RemoteQueryProcessor((SparqlRemoteEndpoint)temp); } else { throw new DotNetRdfConfigurationException("Unable to load the Remote Query Processor identified by the Node '" + objNode.ToSafeString() + "' as the value given for the dnr:endpoint property points to an Object that cannot be loaded as an object which is a SparqlRemoteEndpoint"); } break; case PelletQueryProcessor: String server = ConfigurationLoader.GetConfigurationValue(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyServer))); if (server == null) { return(false); } String kb = ConfigurationLoader.GetConfigurationString(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyStore))); if (kb == null) { return(false); } processor = new PelletQueryProcessor(UriFactory.Create(server), kb); break; } obj = processor; return(processor != null); }
public void StorageVirtuosoBlankNodeDelete() { //First ensure data is present in the store VirtuosoManager manager = VirtuosoTest.GetConnection(); try { manager.DeleteGraph("http://localhost/deleteBNodeTest"); Graph g = new Graph(); Triple t = new Triple(g.CreateBlankNode(), g.CreateUriNode("rdf:type"), g.CreateUriNode(UriFactory.Create("http://example.org/object"))); g.Assert(t); manager.UpdateGraph("http://localhost/deleteBNodeTest", t.AsEnumerable(), null); Object results = manager.Query("ASK WHERE { GRAPH <http://localhost/deleteBNodeTest> { ?s a <http://example.org/object> } }"); if (results is SparqlResultSet) { TestTools.ShowResults(results); Assert.IsTrue(((SparqlResultSet)results).Result, "Expected a true result"); //Now we've ensured data is present we can first load the graph and then try to delete the given triple Graph h = new Graph(); manager.LoadGraph(h, "http://localhost/deleteBNodeTest"); Assert.AreEqual(g, h, "Graphs should be equal"); //Then we can go ahead and delete the triples from this graph manager.UpdateGraph("http://localhost/deleteBNodeTest", null, h.Triples); Graph i = new Graph(); manager.LoadGraph(i, "http://localhost/deleteBNodeTest"); Assert.IsTrue(i.IsEmpty, "Graph should be empty"); Assert.AreNotEqual(h, i); Assert.AreNotEqual(g, i); } else { Assert.Fail("Didn't get a SPARQL Result Set as expected"); } } finally { if (manager != null) { manager.Dispose(); } } }
/* * * Checks whether the SP ontology is used in a given Model. * This is true if the model defines the SP namespace prefix * and also has sp:Query defined with an rdf:type. * The goal of this call is to be very fast when SP is not * imported, i.e. it checks the namespace first and can then * omit the type query. * @param model the Model to check * @return true if SP exists in model */ public static bool existsModel(IGraph model) { return(model != null && model.NamespaceMap.GetPrefix(UriFactory.Create(SP.NS_URI)) != null && model.GetTriplesWithSubjectPredicate(SP.ClassQuery, RDF.PropertyType).Any()); }
/// <summary> /// Evaluates the Graph Clause by setting up the dataset, applying the pattern and then generating additional bindings if necessary /// </summary> /// <param name="context">Evaluation Context</param> /// <returns></returns> public BaseMultiset Evaluate(SparqlEvaluationContext context) { // Q: Can we optimise GRAPH when the input is the Null Multiset to just return the Null Multiset? bool datasetOk = false; try { List <String> activeGraphs = new List <string>(); // Get the URIs of Graphs that should be evaluated over if (this._graphSpecifier.TokenType != Token.VARIABLE) { switch (this._graphSpecifier.TokenType) { case Token.URI: case Token.QNAME: Uri activeGraphUri = UriFactory.Create(Tools.ResolveUriOrQName(this._graphSpecifier, context.Query.NamespaceMap, context.Query.BaseUri)); if (context.Data.HasGraph(activeGraphUri)) { // If the Graph is explicitly specified and there are FROM/FROM NAMED present then the Graph // URI must be in the graphs specified by a FROM/FROM NAMED or the result is null if (context.Query == null || ((!context.Query.DefaultGraphs.Any() && !context.Query.NamedGraphs.Any()) || context.Query.NamedGraphs.Any(u => EqualityHelper.AreUrisEqual(activeGraphUri, u))) ) { // Either there was no Query // OR there were no Default/Named Graphs (hence any Graph URI is permitted) // OR the specified URI was a Named Graph URI // In any case we can go ahead and set the active Graph activeGraphs.Add(activeGraphUri.AbsoluteUri); } else { // The specified URI was not present in the Named Graphs so return null context.OutputMultiset = new NullMultiset(); return(context.OutputMultiset); } } else { // If specifies a specific Graph and not in the Dataset result is a null multiset context.OutputMultiset = new NullMultiset(); return(context.OutputMultiset); } break; default: throw new RdfQueryException("Cannot use a '" + this._graphSpecifier.GetType().ToString() + "' Token to specify the Graph for a GRAPH clause"); } } else { String gvar = this._graphSpecifier.Value.Substring(1); // Watch out for the case in which the Graph Variable is not bound for all Sets in which case // we still need to operate over all Graphs if (context.InputMultiset.ContainsVariable(gvar) && context.InputMultiset.Sets.All(s => s[gvar] != null)) { // If there are already values bound to the Graph variable for all Input Solutions then we limit the Query to those Graphs List <Uri> graphUris = new List <Uri>(); foreach (ISet s in context.InputMultiset.Sets) { INode temp = s[gvar]; if (temp == null) { continue; } if (temp.NodeType != NodeType.Uri) { continue; } activeGraphs.Add(temp.ToString()); graphUris.Add(((IUriNode)temp).Uri); } } else { // Nothing yet bound to the Graph Variable so the Query is over all the named Graphs if (context.Query != null && context.Query.NamedGraphs.Any()) { // Query specifies one/more named Graphs activeGraphs.AddRange(context.Query.NamedGraphs.Select(u => u.AbsoluteUri)); } else if (context.Query != null && context.Query.DefaultGraphs.Any() && !context.Query.NamedGraphs.Any()) { // Gives null since the query dataset does not include any named graphs context.OutputMultiset = new NullMultiset(); return(context.OutputMultiset); } else { // Query is over entire dataset/default Graph since no named Graphs are explicitly specified activeGraphs.AddRange(context.Data.GraphUris.Select(u => u.ToSafeString())); } } } // Remove all duplicates from Active Graphs to avoid duplicate results activeGraphs = activeGraphs.Distinct().ToList(); // Evaluate the inner pattern BaseMultiset initialInput = context.InputMultiset; BaseMultiset finalResult = new Multiset(); // Evalute for each Graph URI and union the results foreach (String uri in activeGraphs) { // Always use the same Input for each Graph URI and set that Graph to be the Active Graph // Be sure to translate String.Empty back to the null URI to select the default graph // correctly context.InputMultiset = initialInput; Uri currGraphUri = (uri.Equals(String.Empty)) ? null : UriFactory.Create(uri); // Set Active Graph if (currGraphUri == null) { // GRAPH operates over named graphs only so default graph gets skipped continue; } // The result of the HasGraph() call is ignored we just make it so datasets with any kind of // load on demand behaviour work properly context.Data.HasGraph(currGraphUri); // All we actually care about is setting the active graph context.Data.SetActiveGraph(currGraphUri); datasetOk = true; // Evaluate for the current Active Graph BaseMultiset result = context.Evaluate(this._pattern); // Merge the Results into our overall Results if (result is NullMultiset) { // Don't do anything, adds nothing to the results } else if (result is IdentityMultiset) { // Adds a single row to the results if (this._graphSpecifier.TokenType == Token.VARIABLE) { // Include graph variable if not yet bound INode currGraph = new UriNode(null, currGraphUri); Set s = new Set(); s.Add(this._graphSpecifier.Value.Substring(1), currGraph); finalResult.Add(s); } else { finalResult.Add(new Set()); } } else { // If the Graph Specifier is a Variable then we must either bind the // variable or eliminate solutions which have an incorrect value for it if (this._graphSpecifier.TokenType == Token.VARIABLE) { String gvar = this._graphSpecifier.Value.Substring(1); INode currGraph = new UriNode(null, currGraphUri); foreach (int id in result.SetIDs.ToList()) { ISet s = result[id]; if (s[gvar] == null) { // If Graph Variable is not yet bound for solution bind it s.Add(gvar, currGraph); } else if (!s[gvar].Equals(currGraph)) { // If Graph Variable is bound for solution and doesn't match // current Graph then we have to remove the solution result.Remove(id); } } } // Union solutions into the Results finalResult.Union(result); } // Reset the Active Graph after each pass context.Data.ResetActiveGraph(); datasetOk = false; } // Return the final result if (finalResult.IsEmpty) { finalResult = new NullMultiset(); } context.OutputMultiset = finalResult; } finally { if (datasetOk) { context.Data.ResetActiveGraph(); } } return(context.OutputMultiset); }
protected void RunManifest(String file, INode[] positiveSyntaxTests, INode[] negativeSyntaxTests) { if (!File.Exists(file)) { Assert.Fail("Manifest file " + file + " not found"); } Graph manifest = new Graph(); manifest.BaseUri = BaseUri; try { manifest.LoadFromFile(file); } catch (Exception ex) { TestTools.ReportError("Bad Manifest", ex); Assert.Fail("Failed to load Manifest " + file); } manifest.NamespaceMap.AddNamespace("rdf", UriFactory.Create("http://www.w3.org/ns/rdftest#")); String findTests = @"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> prefix mf: <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#> prefix qt: <http://www.w3.org/2001/sw/DataAccess/tests/test-query#> prefix rdft: <http://www.w3.org/ns/rdftest#> SELECT ?name ?input ?comment ?result ?type WHERE { { ?test mf:action [ qt:data ?input ] . } UNION { ?test mf:action ?input . FILTER(!ISBLANK(?input)) } OPTIONAL { ?test a ?type } OPTIONAL { ?test mf:name ?name } OPTIONAL { ?test rdfs:comment ?comment } OPTIONAL { ?test mf:result ?result } }"; SparqlResultSet tests = manifest.ExecuteQuery(findTests) as SparqlResultSet; if (tests == null) { Assert.Fail("Failed to find tests in the Manifest"); } foreach (SparqlResult test in tests) { INode nameNode, inputNode, commentNode, resultNode; String name = test.TryGetBoundValue("name", out nameNode) ? nameNode.ToString() : null; inputNode = test["input"]; String input = this.GetFile(inputNode); String comment = test.TryGetBoundValue("comment", out commentNode) ? commentNode.ToString() : null; String results = test.TryGetBoundValue("result", out resultNode) ? this.GetFile(resultNode) : null; //Determine expected outcome //Evaluation tests will have results and should always parse succesfully bool?shouldParse = results != null ? true : false; if (!shouldParse.Value) { //No results declared so may be a positive/negative syntax test //Inspect returned type to determine, if no type assume test should fail INode type; if (test.TryGetBoundValue("type", out type)) { if (positiveSyntaxTests.Contains(type)) { shouldParse = true; } else if (negativeSyntaxTests.Contains(type)) { shouldParse = false; } else { //Unable to determine what the expected result is shouldParse = null; } } } this.RunTest(name, comment, input, results, shouldParse); } }
/// <summary> /// Processes SPARQL Update requests /// </summary> /// <param name="context">HTTP Context</param> public void ProcessRequest(HttpContext context) { this._config = this.LoadConfig(context); WebContext webContext = new WebContext(context); // Add our Standard Headers HandlerHelper.AddStandardHeaders(webContext, this._config); // Options we need to determine based on the HTTP Method used String[] updates; String updateText = null; List <String> userDefaultGraphs = new List <String>(); List <String> userNamedGraphs = new List <String>(); try { // Decide what to do based on the HTTP Method switch (context.Request.HttpMethod.ToUpper()) { case "OPTIONS": // OPTIONS requests always result in the Service Description document IGraph svcDescrip = SparqlServiceDescriber.GetServiceDescription(this._config, UriFactory.Create(context.Request.Url.AbsoluteUri)); HandlerHelper.SendToClient(webContext, svcDescrip, this._config); return; case "HEAD": // Just return from a HEAD request return; case "GET": // A GET with an update parameter is a Bad Request updates = context.Request.QueryString.GetValues("update"); if (updates != null && updates.Length > 0) { throw new ArgumentException("Updates cannot be submitted as GET requests"); } // Otherwise GET either results in the Service Description if appropriately conneg'd or // the update form if enabled try { // If we might show the Update Form only show the Description if the selected writer is // not a HTML writer MimeTypeDefinition definition = MimeTypesHelper.GetDefinitions(webContext.GetAcceptTypes()).FirstOrDefault(d => d.CanWriteRdf); if (definition != null) { IRdfWriter writer = definition.GetRdfWriter(); if (!(writer is IHtmlWriter)) { // If not a HTML Writer selected then show the Service Description Graph // unless an error occurs creating it IGraph serviceDescrip = SparqlServiceDescriber.GetServiceDescription(this._config, UriFactory.Create(context.Request.Url.AbsoluteUri)); context.Response.ContentType = definition.CanonicalMimeType; context.Response.ContentEncoding = definition.Encoding; writer.Save(serviceDescrip, new StreamWriter(context.Response.OutputStream, definition.Encoding)); return; } } } catch { // Ignore Exceptions - we'll just show the Query Form or return a 400 Bad Request instead } // If a Writer can't be selected then we'll either show the Update Form or return a 400 Bad Request if (this._config.ShowUpdateForm) { this.ShowUpdateForm(context); } else { throw new ArgumentException("Updates cannot be submitted as GET requests"); } return; case "POST": if (context.Request.ContentType != null) { MimeTypeSelector contentType = MimeTypeSelector.Create(context.Request.ContentType, 0); if (contentType.Type.Equals(MimeTypesHelper.WWWFormURLEncoded)) { // Form URL Encoded was declared type so expect an update parameter in the Form parameters updates = context.Request.Form.GetValues("update"); if (updates == null) { throw new ArgumentException("Required update parameter in POST body was missing"); } if (updates.Length == 0) { throw new ArgumentException("Required update parameter in POST body was missing"); } if (updates.Length > 1) { throw new ArgumentException("The update parameter was specified multiple times in the POST body"); } updateText = updates[0]; // For Form URL Encoded the Using/Using Named Graphs may be specified by Form parameters // Get the USING URIs (if any) if (context.Request.Form["using-graph-uri"] != null) { userDefaultGraphs.AddRange(context.Request.Form.GetValues("using-graph-uri")); } // Get the USING NAMED URIs (if any) if (context.Request.Form["using-named-graph-uri"] != null) { userNamedGraphs.AddRange(context.Request.Form.GetValues("using-named-graph-uri")); } break; } else if (contentType.Type.Equals(MimeTypesHelper.SparqlUpdate)) { // application/sparql-update was declared type so expect utf-8 charset (if present) if (contentType.Charset != null && !contentType.Charset.ToLower().Equals(MimeTypesHelper.CharsetUtf8)) { throw new ArgumentException("HTTP POST request was received with a " + MimeTypesHelper.SparqlUpdate + " Content-Type but a non UTF-8 charset parameter"); } using (StreamReader reader = new StreamReader(context.Request.InputStream)) { updateText = reader.ReadToEnd(); reader.Close(); } // For application/sparql-update the Using/Using Named Graphs may be specified by querystring parameters // Get the USING URIs (if any) if (context.Request.QueryString["using-graph-uri"] != null) { userDefaultGraphs.AddRange(context.Request.QueryString.GetValues("using-graph-uri")); } // Get the USING NAMED URIs (if any) if (context.Request.QueryString["using-named-graph-uri"] != null) { userNamedGraphs.AddRange(context.Request.QueryString.GetValues("using-named-graph-uri")); } break; } else { throw new ArgumentException("HTTP POST made to SPARQL update endpoint had an invalid Content-Type header, only " + MimeTypesHelper.WWWFormURLEncoded + " and " + MimeTypesHelper.SparqlUpdate + " are acceptable"); } } throw new ArgumentException("HTTP POST made to SPARQL Query endpoint was missing the required Content-Type header"); default: throw new NotSupportedException("HTTP " + context.Request.HttpMethod.ToUpper() + " is not supported by a SPARQL Update endpoint"); } // Clean up protocol provided dataset userDefaultGraphs.RemoveAll(g => String.IsNullOrEmpty(g)); userNamedGraphs.RemoveAll(g => String.IsNullOrEmpty(g)); // Now we're going to parse the Updates SparqlUpdateParser parser = new SparqlUpdateParser(); parser.DefaultBaseUri = context.Request.Url; parser.ExpressionFactories = this._config.ExpressionFactories; SparqlUpdateCommandSet commands = parser.ParseFromString(updateText); // Check whether we need to use authentication // If there are no user groups then no authentication is in use so we default to authenticated with no per-action authentication needed bool isAuth = true, requireActionAuth = false; if (this._config.UserGroups.Any()) { // If we have user isAuth = HandlerHelper.IsAuthenticated(webContext, this._config.UserGroups); requireActionAuth = true; } if (!isAuth) { return; } // First check actions to see whether they are all permissible and apply USING/USING NAMED parameters foreach (SparqlUpdateCommand cmd in commands.Commands) { // Authenticate each action bool actionAuth = true; if (requireActionAuth) { actionAuth = HandlerHelper.IsAuthenticated(webContext, this._config.UserGroups, this.GetPermissionAction(cmd)); } if (!actionAuth) { throw new SparqlUpdatePermissionException("You are not authorised to perform the " + this.GetPermissionAction(cmd) + " action"); } // Check whether we need to (and are permitted to) apply USING/USING NAMED parameters if (userDefaultGraphs.Count > 0 || userNamedGraphs.Count > 0) { BaseModificationCommand modify = cmd as BaseModificationCommand; if (modify != null) { if (modify.GraphUri != null || modify.UsingUris.Any() || modify.UsingNamedUris.Any()) { // Invalid if a command already has a WITH/USING/USING NAMED throw new SparqlUpdateMalformedException("A command in your update request contains a WITH/USING/USING NAMED clause but you have also specified one/both of the using-graph-uri or using-named-graph-uri parameters which is not permitted by the SPARQL Protocol"); } else { // Otherwise go ahead and apply userDefaultGraphs.ForEach(u => modify.AddUsingUri(UriFactory.Create(u))); userNamedGraphs.ForEach(u => modify.AddUsingNamedUri(UriFactory.Create(u))); } } } } // Then assuming we got here this means all our actions are permitted so now we can process the updates this.ProcessUpdates(commands); // Flush outstanding changes this._config.Processor.Flush(); // Update the Cache as the request may have changed the endpoint this.UpdateConfig(context); } catch (RdfParseException parseEx) { HandleErrors(context, "Parsing Error", updateText, parseEx, (int)HttpStatusCode.BadRequest); } catch (SparqlUpdatePermissionException permEx) { HandleErrors(context, "Permissions Error", updateText, permEx, (int)HttpStatusCode.Forbidden); } catch (SparqlUpdateMalformedException malEx) { HandleErrors(context, "Malformed Update Error", updateText, malEx, (int)HttpStatusCode.BadRequest); } catch (SparqlUpdateException updateEx) { HandleErrors(context, "Update Error", updateText, updateEx); } catch (RdfException rdfEx) { HandleErrors(context, "RDF Error", updateText, rdfEx); } catch (NotSupportedException notSupEx) { HandleErrors(context, "HTTP Request Error", null, notSupEx, (int)HttpStatusCode.MethodNotAllowed); } catch (ArgumentException argEx) { HandleErrors(context, "HTTP Request Error", null, argEx, (int)HttpStatusCode.BadRequest); } catch (Exception ex) { HandleErrors(context, "Error", updateText, ex); } }
/// <summary> /// Creates a new boolean valued node. /// </summary> /// <param name="g">Graph the node belong to.</param> /// <param name="value">Boolean Value.</param> /// <param name="lexicalValue">Lexical Value.</param> public BooleanNode(IGraph g, bool value, String lexicalValue) : base(g, lexicalValue, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeBoolean)) { _value = value; }
/// <summary> /// Clears all values for a Literal Property /// </summary> /// <param name="propertyUri">Property URI</param> /// <param name="persist">Whether the removed values are removed from the Graph</param> public bool ClearLiteralProperty(String propertyUri, bool persist) { if (_literalProperties.ContainsKey(propertyUri)) { _literalProperties[propertyUri].Clear(); if (persist) { _graph.Retract(_graph.GetTriplesWithSubjectPredicate(_resource, _graph.CreateUriNode(UriFactory.Create(propertyUri))).ToList()); } return(true); } else { return(false); } }
/// <summary> /// Tries to load a Reasoner based on information from the Configuration Graph. /// </summary> /// <param name="g">Configuration Graph.</param> /// <param name="objNode">Object Node.</param> /// <param name="targetType">Target Type.</param> /// <param name="obj">Output Object.</param> /// <returns></returns> public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj) { obj = null; Object output; switch (targetType.FullName) { case PelletReasonerType: String server = ConfigurationLoader.GetConfigurationValue(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyServer))); if (server == null) return false; String kb = ConfigurationLoader.GetConfigurationString(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyStore))); if (kb == null) return false; output = new PelletReasoner(UriFactory.Create(server), kb); break; case OwlReasonerWrapperType: INode reasonerNode = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyOwlReasoner))); if (reasonerNode == null) return false; Object reasoner = ConfigurationLoader.LoadObject(g, reasonerNode); if (reasoner is IOwlReasoner) { output = new OwlReasonerWrapper((IOwlReasoner)reasoner); } else { throw new DotNetRdfConfigurationException("Unable to load configuration for the OWL Reasoner Wrapper identified by the Node '" + objNode.ToString() + "' as the value for the dnr:owlReasoner property points to an Object which cannot be loaded as an object which implements the IOwlReasoner interface"); } break; default: // Otherwise we'll just attempt to load this as an instance of an IInferenceEngine try { output = (IInferenceEngine)Activator.CreateInstance(targetType); } catch { // Any error means this loader can't load this type return false; } break; } if (output != null) { if (output is IInferenceEngine) { // Now initialise with any specified Graphs IEnumerable<INode> rulesGraphs = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingGraph))); foreach (INode rulesGraph in rulesGraphs) { Object temp = ConfigurationLoader.LoadObject(g, rulesGraph); if (temp is IGraph) { ((IInferenceEngine)output).Initialise((IGraph)temp); } else { throw new DotNetRdfConfigurationException("Unable to load Configuration for the Forward Chaining Reasoner identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:usingGraph property points to an Object which cannot be loaded as an object which implements the IGraph interface"); } } } } obj = output; return true; }