コード例 #1
0
ファイル: SparqlTriple.cs プロジェクト: Sergey303/RDF-Store
        private IEnumerable <SparqlResult> CreateBindings(SparqlResult variableBinding)
        {
            this.Subject   = this.sVariableNode != null ? variableBinding[this.sVariableNode] : this.Subject;
            this.Predicate = this.pVariableNode != null ? variableBinding[this.pVariableNode] : this.Predicate;
            this.Object    = this.oVariableNode != null ? variableBinding[this.oVariableNode] : this.Object;


            if (!this.PrepareKnownVarValues())
            {
                return(Enumerable.Empty <SparqlResult>());
            }
            if (!this.isDefaultGraph && this.variableDataSet != null)
            {
                var graphFromVar = variableBinding[this.variableDataSet.Variable];
                this.graphs = graphFromVar != null ? new DataSet()
                {
                    graphFromVar
                } : null;
                this.isGKnown = this.graphs != null;
            }
            else
            {
                this.isGKnown = true;
            }

            int @case = ((this.Subject != null ? 0 : 1) << 2) | ((this.Predicate != null ? 0 : 1) << 1) | (this.Object != null ? 0 : 1);

            if (!this.isDefaultGraph)
            {
                @case |= 1 << (this.isGKnown ? 3 : 4);
            }
            return(this.ClearNewValues(this.Subject == null, this.Predicate == null, this.Object == null, !this.isGKnown, variableBinding, this.listOfFilters.Count > 0 ? this.SetVariablesValuesWithFilters(variableBinding, (StoreCallCase)@case) : this.SetVariablesValues(variableBinding, (StoreCallCase)@case)));
        }
コード例 #2
0
ファイル: SparqlTriple.cs プロジェクト: Sergey303/RDF-Store
 private IEnumerable <SparqlResult> spoGraphs(SparqlResult variablesBindings)
 {
     if (this.graphs.Any(g => this.store.NamedGraphs.Contains(this.Subject, this.Predicate, this.Object, g)))
     {
         yield return(variablesBindings);
     }
 }
コード例 #3
0
        private IEnumerable <SparqlResult> CreateBindings(SparqlResult variableBinding)
        {
            Subject   = sVariableNode != null ? variableBinding[sVariableNode] : Subject;
            Predicate = pVariableNode != null ? variableBinding[pVariableNode] : Predicate;
            Object    = oVariableNode != null ? variableBinding[oVariableNode] : Object;


            if (!PrepareKnownVarValues())
            {
                return(Enumerable.Empty <SparqlResult>());
            }
            if (!isDefaultGraph && variableDataSet != null)
            {
                var graphFromVar = variableBinding[variableDataSet.Variable];
                graphs = graphFromVar != null ? new DataSet()
                {
                    graphFromVar
                } : null;
                isGKnown = graphs != null;
            }
            else
            {
                isGKnown = true;
            }

            int @case = ((Subject != null ? 0 : 1) << 2) | ((Predicate != null ? 0 : 1) << 1) | (Object != null ? 0 : 1);

            if (!isDefaultGraph)
            {
                @case |= 1 << (isGKnown ? 3 : 4);
            }
            return(ClearNewValues(Subject == null, Predicate == null, Object == null, !isGKnown, variableBinding,
                                  listOfFilters.Count > 0 ? SetVariablesValuesWithFilters(variableBinding, (StoreCallCase)@case) :  SetVariablesValues(variableBinding, (StoreCallCase)@case)));
        }
コード例 #4
0
 public  IEnumerable<SparqlResult> spOGraphs( ObjectVariants subjNode, ObjectVariants predicateNode,
     VariableNode obj, SparqlResult variablesBindings, DataSet graphs)
 {
     return spOCacheGraphs(subjNode, predicateNode,graphs)
         .SelectMany(grouping =>
                 grouping.Select(node => new SparqlResult(variablesBindings, node, obj)));     
 }
コード例 #5
0
        private void TestDataContractSerialization(SparqlResult r, bool fullEquality)
        {
            Console.WriteLine("Input: " + r.ToString());

            System.IO.StringWriter writer     = new System.IO.StringWriter();
            DataContractSerializer serializer = new DataContractSerializer(typeof(SparqlResult));

            serializer.WriteObject(new XmlTextWriter(writer), r);
            Console.WriteLine("Serialized Form:");
            Console.WriteLine(writer.ToString());

            SparqlResult s = serializer.ReadObject(XmlTextReader.Create(new StringReader(writer.ToString()))) as SparqlResult;

            Console.WriteLine("Deserialized Form: " + s.ToString());
            Console.WriteLine();

            if (fullEquality)
            {
                Assert.Equal(r, s);
            }
            else
            {
                Assert.Equal(r.ToString(), s.ToString());
            }
        }
コード例 #6
0
        protected override void ProcessResult(SparqlResult result)
        {
            var nvc = new NameValueCollection();

            foreach (string varName in varNames)
            {
                if (!result.HasValue(varName)) continue;

                INode resource = result[varName];

                if (resource.NodeType == NodeType.Uri)
                {
                    if (string.IsNullOrEmpty(@namespace) || ((IUriNode)resource).ToString().StartsWith(@namespace))
                    {
                        nvc[varName] = resource.ToString();
                    }
                }
                else if (resource.NodeType == NodeType.Blank && !ignoreBnodes)
                {
                    var bn = resource as BlankNode;
                    if (string.IsNullOrEmpty(@namespace) || bn.InternalID.StartsWith(@namespace))
                    {
                        nvc[varName] = bn.InternalID;
                    }
                }
            }
            bindings.Add(nvc);
        }
コード例 #7
0
        protected override void ProcessResult(SparqlResult result)
        {
            var nvc = new NameValueCollection();

            foreach (string varName in varNames)
            {
                if (!result.HasValue(varName))
                {
                    continue;
                }

                INode resource = result[varName];

                if (resource.NodeType == NodeType.Uri)
                {
                    if (string.IsNullOrEmpty(@namespace) || ((IUriNode)resource).ToString().StartsWith(@namespace))
                    {
                        nvc[varName] = resource.ToString();
                    }
                }
                else if (resource.NodeType == NodeType.Blank && !ignoreBnodes)
                {
                    var bn = resource as BlankNode;
                    if (string.IsNullOrEmpty(@namespace) || bn.InternalID.StartsWith(@namespace))
                    {
                        nvc[varName] = bn.InternalID;
                    }
                }
            }
            bindings.Add(nvc);
        }
コード例 #8
0
        private static bool CompareSolutions(SparqlResult x, SparqlResult y, Dictionary <string, string> bnodeMap)
        {
            var boundVarsX = x.Variables.Where(v => x.HasValue(v) && x.Value(v) != null);
            var boundVarsY = y.Variables.Where(v => y.HasValue(v) && y.Value(v) != null);

            if (!boundVarsX.Any() && !boundVarsY.Any())
            {
                return(true);
            }
            if (x.Variables.Count().Equals(y.Variables.Count()) &&
                x.Variables.All(xv => y.Variables.Contains(xv)))
            {
                foreach (var xv in x.Variables)
                {
                    var xb = x[xv];
                    var yb = y[xv];
                    if (!CompareNodes(xb, yb, bnodeMap))
                    {
                        return(false);
                    }
                }
                return(true);
            }
            return(false);
        }
コード例 #9
0
        public ActionResult SearchDetails(string query)
        {
            //ako je autor prikazi detalje autora

            //inace prikazi detalje filma

            if (searchPoFilmu)
            {
                SparqlResultSet detaljiFilma = endpoint.QueryWithResultSet("PREFIX movie: <http://data.linkedmdb.org/resource/movie/> PREFIX dc: <http://purl.org/dc/terms/> SELECT distinct ?title ?genreName ?dirName ?editorName ?date WHERE {?movie dc:title ?title . ?movie movie:genre ?genre. ?genre movie:film_genre_name ?genreName. ?movie movie:director ?director. ?director movie:director_name ?dirName. ?movie movie:editor ?editor. ?editor movie:editor_name ?editorName. ?movie dc:date ?date  FILTER REGEX (?title, '" + query + "', 'i') }ORDER BY ASC(?title) ");

                Movie m = new Movie();
                if (detaljiFilma.Count > 0)
                {
                    SparqlResult result = detaljiFilma[0];
                    m.name          = ((VDS.RDF.BaseLiteralNode)(result[0])).Value;
                    m.scenarist     = ((VDS.RDF.BaseLiteralNode)(result[2])).Value;
                    m.redatelj      = ((VDS.RDF.BaseLiteralNode)(result[3])).Value;
                    m.datumNastanka = ((VDS.RDF.BaseLiteralNode)(result[4])).Value;
                }
                return(View("~/Views/Search/Movie.cshtml", m));
            }

            if (searchPoGlumcu)
            {
                Actor actor = new Models.Actor();

                return(View("~/Views/Search/Actor.cshtml", actor));
            }

            return(View("~/Views/Search/NoResult.cshtml"));
        }
コード例 #10
0
 public Provenance(SparqlResult result)
 {
     DateAcquired = result.Value("dateAcquired").ToString();
     Location     = result.Value("location").ToString();
     OwnedBy      = result.Value("ownerLabel").ToString();
     DispayOrder  = result.Value("dispayOrder").ToString();
 }
        public SparqlResponseProperty GetNodeValuesFromSparqlResult(SparqlResult sparqlResult, string value)
        {
            INode node;
            var   data = new SparqlResponseProperty();

            if (sparqlResult.TryGetValue(value, out node))
            {
                if (node != null)
                {
                    data.Type = node.NodeType.ToString().ToLower();
                    switch (node.NodeType)
                    {
                    case NodeType.Uri:
                        data.Value = ((IUriNode)node).Uri.AbsoluteUri;
                        break;

                    case NodeType.Blank:
                        data.Value = ((IBlankNode)node).InternalID;
                        break;

                    case NodeType.Literal:
                        //You may want to inspect the DataType and Language properties and generate
                        //a different string here
                        data.Value    = ((ILiteralNode)node).Value;
                        data.DataType = ((ILiteralNode)node).DataType?.OriginalString;
                        break;

                    default:
                        throw new RdfOutputException("Unexpected Node Type");
                    }
                }
            }
            return(data);
        }
コード例 #12
0
        private void TestBinarySerialization(SparqlResult r, bool fullEquality)
        {
            MemoryStream    stream     = new MemoryStream();
            BinaryFormatter serializer = new BinaryFormatter(null, new StreamingContext());

            serializer.Serialize(stream, r);

            stream.Seek(0, SeekOrigin.Begin);
            Console.WriteLine("Serialized Form:");
            StreamReader reader = new StreamReader(stream);

            Console.WriteLine(reader.ReadToEnd());

            stream.Seek(0, SeekOrigin.Begin);
            SparqlResult s = serializer.Deserialize(stream) as SparqlResult;

            reader.Close();

            if (fullEquality)
            {
                Assert.AreEqual(r, s, "Results should be equal");
            }
            else
            {
                Assert.AreEqual(r.ToString(), s.ToString(), "String forms should be equal");
            }

            stream.Dispose();
        }
コード例 #13
0
        private void TestXmlSerialization(SparqlResult r, bool fullEquality)
        {
            Console.WriteLine("Input: " + r.ToString());

            System.IO.StringWriter writer     = new System.IO.StringWriter();
            XmlSerializer          serializer = new XmlSerializer(typeof(SparqlResult));

            serializer.Serialize(writer, r);
            Console.WriteLine("Serialized Form:");
            Console.WriteLine(writer.ToString());

            SparqlResult s = serializer.Deserialize(new StringReader(writer.ToString())) as SparqlResult;

            Console.WriteLine("Deserialized Form: " + s.ToString());
            Console.WriteLine();

            if (fullEquality)
            {
                Assert.AreEqual(r, s, "Results should be equal");
            }
            else
            {
                Assert.AreEqual(r.ToString(), s.ToString(), "String forms should be equal");
            }
        }
コード例 #14
0
        /// <summary>
        /// Extracts the corresponding value from the SemWeb results for a member access projection.
        /// </summary>
        /// <param name="vb">The SemWeb results.</param>
        /// <returns>the value that was extracted (and converted) from the results.</returns>
        private object ExtractMemberAccess(SparqlResult vb)
        {
            // work out if the SelectExpression really is a member access
            var ue = (SelectExpression).Arguments[1] as UnaryExpression;

            if (ue == null)
            {
                throw new ArgumentException("incompatible expression type");
            }

            var le = ue.Operand as LambdaExpression;

            if (le == null)
            {
                throw new LinqToRdfException("Incompatible expression type found when building ontology projection");
            }

            if (le.Body is MemberExpression)
            {
                // work out which member is being queried on
                var        memberExpression = (MemberExpression)le.Body;
                MemberInfo memberInfo       = memberExpression.Member;
                // get its name and use that as a key into the results
                //string vVal = vb[memberInfo.Name].ToString();
                // convert the result from XSDT format to .NET types
                if (!vb.HasValue(memberInfo.Name))
                {
                    return(null);
                }
                var tc = new XsdtTypeConverter();
                return(tc.Parse(vb[memberInfo.Name]));
                //return tc.Parse(vVal);
            }
            return(null);
        }
コード例 #15
0
        /// <summary>
        /// Assigns the instance URI from the SPARQL result bindings.
        /// </summary>
        /// <param name="obj">The object to assign the URI to.</param>
        /// <param name="queryAlias">The query alias that was used in LINQ and SPARQL.</param>
        /// <param name="semwebResult">The semweb result to take the value from.</param>
        private void AssignInstanceUri(OwlInstanceSupertype obj, string queryAlias,
                                       SparqlResult result)
        {
            // if there is no alias, then there's no way to work out what contains the instance URI
            if (string.IsNullOrEmpty(queryAlias))
            {
                return;
            }

            // if there is a binding with the same name as the alias
            if (result.Variables.Contains(queryAlias))
            {
                // get string representation of the instance URI
                string uri = result[queryAlias].ToString();

                // is it enclosed in angle brackets? then strip them.
                if (uri.StartsWith("<") && uri.EndsWith(">"))
                {
                    uri = uri.Substring(1, uri.Length - 2);
                }

                // can this be parsed as a URI? if so then assign to instance URI property of obj
                if (Uri.IsWellFormedUriString(uri, UriKind.RelativeOrAbsolute))
                {
                    obj.InstanceUri = uri;
                }
            }
        }
コード例 #16
0
 public IEnumerable <SparqlResult> spO(ObjectVariants subjNode, ObjectVariants predicateNode,
                                       VariableNode obj, SparqlResult variablesBindings)
 {
     return(store.GetTriplesWithSubjectPredicate(subjNode, predicateNode)
            .ToArray()
            .Select(node => variablesBindings.Add(node, obj)));
 }
コード例 #17
0
        static void Main()
        {
            var parser = new Notation3Parser();
            var graph  = new Graph();

            Console.WriteLine("Loading Notation-3 file.");
            //parser.Load(graph, @"n3\ontology.n3");

            parser.Load(graph, @"n3\converter.n3");
            Console.WriteLine("Loaded Notation-3 file.");
            Console.WriteLine("Nodes:");
            foreach (Triple triple in graph.Triples)
            {
                Console.WriteLine("{0} {1} {2}", GetNodeString(triple.Subject), GetNodeString(triple.Predicate), GetNodeString(triple.Object));
            }
            Console.WriteLine();
            Console.WriteLine("Results of 'insomnia' query:");
            Console.WriteLine();
            SparqlResultSet resultSet = graph.ExecuteQuery(getInsomnia) as SparqlResultSet;

            if (resultSet != null)
            {
                Console.WriteLine("Results for variable 'name':");
                for (int i = 0; i < resultSet.Count; i++)
                {
                    SparqlResult result = resultSet[i];
                    Console.WriteLine("{0}. {1}", i + 1, result["name"]);
                }
            }

            Console.ReadLine();
        }
コード例 #18
0
 private void tryAddPerson(SparqlResult i)
 {
     if (!People.ContainsKey(i.Value("person")))
     {
         People.Add(i.Value("person"), i);
     }
 }
コード例 #19
0
        private VisitedPlaceDataObject MapSparqlResultToVisitedPlace(SparqlResult result, bool mapId = true)
        {
            var visitedPlace = new VisitedPlaceDataObject();

            if (mapId)
            {
                visitedPlace.Id = new Guid((result.Where(r => r.Key == "VisitedPlace").Single().Value as UriNode).Uri.Fragment.TrimStart('#'));
            }

            visitedPlace.Date        = DateTime.ParseExact((result.Where(r => r.Key == "Date").Single().Value as BaseLiteralNode).Value, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            visitedPlace.Description = (result.Where(r => r.Key == "Description").Single().Value as BaseLiteralNode)?.Value;

            if (result.Where(r => r.Key == "PlaceOrCountry").Count() == 1)
            {
                visitedPlace.Typeofplace = (PlaceTypesEnum)Enum.Parse(typeof(PlaceTypesEnum), (result.Where(r => r.Key == "PlaceOrCountry").Single().Value as BaseLiteralNode)?.Value);
            }

            if (result.Where(r => r.Key == "CountryURI").Count() == 1)
            {
                visitedPlace.CountryURI = (result.Where(r => r.Key == "CountryURI").Single().Value as UriNode).Uri.ToString();
            }

            if (result.Where(r => r.Key == "PlaceURI").Count() == 1)
            {
                visitedPlace.PlaceURI = (result.Where(r => r.Key == "PlaceURI").Single().Value as UriNode).Uri.ToString();
            }

            visitedPlace.IsNew   = false;
            visitedPlace.IsDirty = false;

            return(visitedPlace);
        }
コード例 #20
0
        public IEnumerable<SparqlResult> spoGraphs(ObjectVariants subjectNode, ObjectVariants predicateNode, ObjectVariants objectNode,
              SparqlResult variablesBindings, DataSet graphs)
        {
            if (spoGraphsCache(subjectNode, predicateNode, objectNode, graphs).Any())
              yield return  variablesBindings;

        }
コード例 #21
0
        private IEnumerable <SparqlResult> CreateBindings(SparqlResult variableBinding)
        {
            Subject   = sVariableNode != null ? variableBinding[sVariableNode] : Subject;
            Predicate = pVariableNode != null ? variableBinding[pVariableNode] : Predicate;
            Object    = oVariableNode != null ? variableBinding[oVariableNode] : Object;

            if (!isDefaultGraph && variableDataSet != null)
            {
                var graphFromVar = variableBinding[variableDataSet.Variable];
                graphs = graphFromVar != null ? new DataSet()
                {
                    graphFromVar
                } : null;
                isGKnown = graphs != null;
            }
            else
            {
                isGKnown = true;
            }

            int @case = ((Subject != null ? 0 : 1) << 2) | ((Predicate != null ? 0 : 1) << 1) | (Object != null ? 0 : 1);

            if (!isDefaultGraph)
            {
                @case |= 1 << (isGKnown ? 3 : 4);
            }
            return(SetVariablesValues(variableBinding, (StoreCallCase)@case));
        }
コード例 #22
0
 private IEnumerable <SparqlResult> spoGraphs(SparqlResult variablesBindings)
 {
     if (graphs.Any(g => q.Store.NamedGraphs.Contains(Subject, Predicate, Object, g)))
     {
         yield return(variablesBindings);
     }
 }
コード例 #23
0
 public IEnumerable <SparqlResult> spOGraphs(ObjectVariants subjNode, ObjectVariants predicateNode,
                                             VariableNode obj, SparqlResult variablesBindings, DataSet graphs)
 {
     return(graphs.SelectMany(graph => store
                              .NamedGraphs
                              .GetObject(subjNode, predicateNode, graph) // if graphs is empty, Gets All named graphs
                              .Select(o => variablesBindings.Add(o, obj))));
 }
コード例 #24
0
 public IEnumerable <SparqlResult> spoVarGraphs(ObjectVariants subjectNode, ObjectVariants predicateNode, ObjectVariants objectNode,
                                                SparqlResult variablesBindings, VariableDataSet graphs)
 {
     return((graphs.Any()
         ? graphs.Where(g => store.NamedGraphs.Contains(subjectNode, predicateNode, objectNode, g))
         : store.NamedGraphs.GetGraph(subjectNode, predicateNode, objectNode))
            .Select(g => variablesBindings.Add(g, graphs.Variable)));
 }
コード例 #25
0
 public static T GetNode <T>(this SparqlResult result, string variable) where T : class
 {
     if (result.TryGetValue(variable, out INode subNode))
     {
         return(subNode as T);
     }
     return(default(T));
 }
コード例 #26
0
 public IEnumerable <SparqlResult> sPOGraphs(ObjectVariants subj, VariableNode pred,
                                             VariableNode obj, SparqlResult variablesBindings, DataSet graphs)
 {
     return(graphs.SelectMany(g => store
                              .NamedGraphs
                              .GetTriplesWithSubjectFromGraph(subj, g, (p, o) =>
                                                              variablesBindings.Add(p, pred, o, obj))));
 }
コード例 #27
0
 /// <summary>
 /// Creates a new Set from a SPARQL Result
 /// </summary>
 /// <param name="result">Result</param>
 internal Set(SparqlResult result)
 {
     this._values = new Dictionary <string, INode>();
     foreach (String var in result.Variables)
     {
         this.Add(var, result[var]);
     }
 }
コード例 #28
0
ファイル: BaseHandler.cs プロジェクト: yuryk53/dotnetrdf
 /// <summary>
 /// Handlers SPARQL Results
 /// </summary>
 /// <param name="result">Result</param>
 /// <returns></returns>
 public bool HandleResult(SparqlResult result)
 {
     if (!this._inUse)
     {
         throw new RdfParseException("Cannot Handle a Result as this Handler is not currently in-use");
     }
     return(this.HandleResultInternal(result));
 }
コード例 #29
0
 private Func <TripleIntOV, SparqlResult> Selector(SparqlResult sparqlResult, VariableNode variable)
 {
     return(t =>
     {
         sparqlResult[variable] = t.Object;
         return sparqlResult;
     });
 }
コード例 #30
0
 public static SearchResult ToSearchResult(this SparqlResult result)
 {
     return(new SearchResult()
     {
         Title = result.GetNode <LiteralNode>("t")?.Value,
         Excerpt = result.GetNode <LiteralNode>("e")?.Value,
         Url = result.GetNode <LiteralNode>("u")?.Value
     });
 }
コード例 #31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DynamicSparqlResult"/> class.
        /// </summary>
        /// <param name="original">The SPARQL result to wrap.</param>
        /// <exception cref="ArgumentNullException">When <paramref name="original"/> is null.</exception>
        public DynamicSparqlResult(SparqlResult original)
        {
            if (original is null)
            {
                throw new ArgumentNullException(nameof(original));
            }

            this.original = original;
        }
コード例 #32
0
ファイル: LogSink.cs プロジェクト: almostEric/DotNetRDF-4.0
 protected override void ProcessResult(SparqlResult result)
 {
     foreach (String variable in result.Variables)
     {
         if (result.HasValue(variable))
         {
             Logger.Debug("?{0} => <{1}>", variable, result[variable]);
         }
     }
 }
コード例 #33
0
ファイル: SparqlXmlFormatter.cs プロジェクト: jmahmud/RDFer
 /// <summary>
 /// Formats a SPARQL Result
 /// </summary>
 /// <param name="result">SPARQL Result</param>
 /// <returns></returns>
 public string Format(SparqlResult result)
 {
     StringBuilder output = new StringBuilder();
     output.AppendLine(" <result>");
     foreach (String var in result.Variables)
     {
         if (result.HasValue(var))
         {
             INode value = result[var];
             if (value != null)
             {
                 output.Append("  <binding name=\"" + var + "\">");
                 switch (value.NodeType)
                 {
                     case NodeType.Blank:
                         output.Append("<bnode>" + ((IBlankNode)value).InternalID + "</bnode>");
                         break;
                     case NodeType.GraphLiteral:
                         throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("SPARQL XML Results"));
                     case NodeType.Literal:
                         ILiteralNode lit = (ILiteralNode)value;
                         output.Append("<literal");
                         if (lit.DataType != null)
                         {
                             output.Append(" datatype=\"" + WriterHelper.EncodeForXml(lit.DataType.ToString()) + "\">" + WriterHelper.EncodeForXml(lit.Value) + "</literal>");
                         }
                         else if (!lit.Language.Equals(String.Empty))
                         {
                             output.Append(" xml:lang=\"" + lit.Language + "\">" + lit.Value + "</literal>");
                         }
                         else
                         {
                             output.Append(">" + WriterHelper.EncodeForXml(lit.Value) + "</literal>");
                         }
                         break;
                     case NodeType.Uri:
                         output.Append("<uri>" + WriterHelper.EncodeForXml(value.ToString()) + "</uri>");
                         break;
                     case NodeType.Variable:
                         throw new RdfOutputException(WriterErrorMessages.VariableNodesUnserializable("SPARQL XML Results"));
                     default:
                         throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("SPARQL XML Results"));
                 }
                 output.AppendLine("</binding>");
             }
         }
     }
     output.Append(" </result>");
     return output.ToString();
 }
コード例 #34
0
 /// <summary>
 /// Handles a Result by adding it to the Result Set
 /// </summary>
 /// <param name="result">Result</param>
 /// <returns></returns>
 protected override bool HandleResultInternal(SparqlResult result)
 {
     this._results.AddResult(result);
     return true;
 }
コード例 #35
0
        /// <summary>
        /// A callback interface that gets called by SemWeb when results are sent 
        /// back from a remote SPARQL source. This gets each unique set of bindings 
        /// in turn. It can either store the results or deserialise them on the spot.
        /// </summary>
        /// <returns>true if the deserialiser was able to use the result or false otherwise</returns>
        protected override void ProcessResult(SparqlResult result)
        {
            #region Tracing

#line hidden
            if (Logger.IsDebugEnabled)
            {
                Logger.Debug("Got Result {0}.", result.ToString());
            }
#line default

            #endregion

            if (IsSelectMember(SelectExpression))
            {
                IncomingResults.Add(ExtractMemberAccess(result));
                return;
            }

            if (originalType == null) throw new LinqToRdfException("need ontology type to create");
            object t;

            IEnumerable<MemberInfo> props = GetPropertiesToPopulate(originalType, instanceType);

            if (originalType == instanceType)
            {
                #region not using a projection

                t = Activator.CreateInstance(instanceType);

                #region Tracing

#line hidden
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug("created new instance of {0}.", t.GetType().Name);
                }
#line default

                #endregion

                AssignDataContext(t as OwlInstanceSupertype, DataContext);
                AssignInstanceUri(t as OwlInstanceSupertype, InstanceName, result);

                foreach (PropertyInfo pi in props)
                {
                    if (pi.PropertyType.IsGenericType &&
                        pi.PropertyType.GetGenericTypeDefinition().Name.StartsWith("Entity"))
                        continue;
                    try
                    {
                        PopulateProperty(result, t, pi);
                    }
                    catch (ArgumentException ae)
                    {
                        #region Tracing

#line hidden
                        if (Logger.IsErrorEnabled)
                        {
                            Logger.ErrorEx("Unable to populate property " + pi.Name, ae);
                            Logger.Error("continuing");
                        }
#line default

                        #endregion
                    }
                    catch (Exception e)
                    {
                        #region Tracing

#line hidden
                        if (Logger.IsErrorEnabled)
                        {
                            Logger.ErrorEx("Unable to populate property " + pi.Name, e);
                        }
#line default

                        #endregion

                        return;
                    }
                }

                #endregion
            }
            else
            {
                #region using a projection

                var args = new List<object>();
                foreach (PropertyInfo pi in props)
                {
                    try
                    {
                        if (result.HasValue(pi.Name))
                        {
                            if (result[pi.Name] != null)
                            {
                               
                                string vVal = result[pi.Name].ToString();
                                vVal = RemoveEnclosingQuotesOnString(vVal, pi);
                                if (IsXsdtEncoded(vVal))
                                    vVal = DecodeXsdtString(vVal);
                                args.Add(Convert.ChangeType(vVal, pi.PropertyType));
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        return;
                    }
                }
                t = Activator.CreateInstance(instanceType, args.ToArray());

                #endregion
            }
            if (Distinct)
            {
                if (ObjectIsUniqueSoFar(t as OwlInstanceSupertype))
                    IncomingResults.Add(t);
            }
            else
                IncomingResults.Add(t);

            return;
        }
コード例 #36
0
ファイル: SPARQLXMLParser.cs プロジェクト: jbunzel/MvcRQ_git
        /// <summary>
        /// Parses the XML Result Set format into a set of SPARQLResult objects
        /// </summary>
        /// <param name="context">Parser Context</param>
        private void Parse(SparqlXmlParserContext context)
        {
            try
            {
                context.Handler.StartResults();

                //Get the Document Element and check it's a Sparql element
                if (!context.Input.Read()) throw new RdfParseException("Unable to Parse a SPARQL Result Set as it was not possible to read a document element from the input");
                while (context.Input.NodeType != XmlNodeType.Element)
                {
                    if (!context.Input.Read()) throw new RdfParseException("Unable to Parse a SPARQL Result Set as it was not possible to read a document element from the input");
                }
                if (!context.Input.Name.Equals("sparql"))
                {
                    throw new RdfParseException("Unable to Parse a SPARQL Result Set from the provided XML since the Document Element is not a <sparql> element!");
                }

                //Go through it's attributes and check the Namespace is specified
                bool nsfound = false;
                if (context.Input.HasAttributes)
                {
                    for (int i = 0; i < context.Input.AttributeCount; i++)
                    {
                        context.Input.MoveToNextAttribute();
                        if (context.Input.Name.Equals("xmlns"))
                        {
                            if (!context.Input.Value.Equals(SparqlSpecsHelper.SparqlNamespace))
                            {
                                throw new RdfParseException("Unable to Parse a SPARQL Result Set since the <sparql> element has an incorrect Namespace!");
                            }
                            else
                            {
                                nsfound = true;
                            }
                        }
                    }
                }
                if (!nsfound)
                {
                    throw new RdfParseException("Unable to Parse a SPARQL Result Set since the <sparql> element fails to specify the SPARQL Namespace!");
                }

                //Get the Variables from the Header
                if (!context.Input.Read()) throw new RdfParseException("Unable to Parse a SPARQL Result Set as could not read a <head> element from the input");
                if (!context.Input.Name.Equals("head"))
                {
                    throw new RdfParseException("Unable to Parse a SPARQL Result Set since the first Child Node of the <sparql> element is not the required <head> element!");
                }

                //Only parser <variable> and <link> elements if not an empty <head /> element
                if (!context.Input.IsEmptyElement)
                {
                    while (context.Input.Read())
                    {
                        //Stop reading when we hit the </head>
                        if (context.Input.NodeType == XmlNodeType.EndElement && context.Input.Name.Equals("head")) break;

                        //Looking for <variable> elements
                        if (context.Input.Name.Equals("variable"))
                        {
                            //Should only have 1 attribute
                            if (context.Input.AttributeCount != 1)
                            {
                                throw new RdfParseException("Unable to Parse a SPARQL Result Set since a <variable> element has too few/many attributes, only a 'name' attribute should be present!");
                            }
                            else
                            {
                                //Add the Variable to the list
                                context.Input.MoveToNextAttribute();
                                if (!context.Handler.HandleVariable(context.Input.Value)) ParserHelper.Stop();
                                context.Variables.Add(context.Input.Value);
                            }
                        }
                        else if (context.Input.Name.Equals("link"))
                        {
                            //Not bothered about <link> elements
                        }
                        else
                        {
                            //Some unexpected element
                            throw new RdfParseException("Unable to Parse a SPARQL Result Set since the <head> contains an unexpected element <" + context.Input.Name + ">!");
                        }
                    }
                }

                if (!context.Input.Name.Equals("head"))
                {
                    throw new RdfParseException("Unable to Parse a SPARQL Result Set as reached the end of the input before the closing </head> element was found");
                }

                //Look at the <results> or <boolean> element
                if (!context.Input.Read()) throw new RdfParseException("Unable to Parse a SPARQL Result Set as could not read a <results> element from the input");
                if (context.Input.Name.Equals("results"))
                {
                    //Only parser <result> elements if it's not an empty <results /> element
                    if (!context.Input.IsEmptyElement)
                    {
                        while (context.Input.Read())
                        {
                            //Stop reading when we hit the </results>
                            if (context.Input.NodeType == XmlNodeType.EndElement && context.Input.Name.Equals("results")) break;

                            //Must be a <result> element
                            if (!context.Input.Name.Equals("result"))
                            {
                                throw new RdfParseException("Unable to Parse a SPARQL Result Set since the <results> element contains an unexpected element <" + context.Input.Name + ">!");
                            }

                            //Empty Elements generate an Empty Result
                            if (context.Input.IsEmptyElement)
                            {
                                if (!context.Handler.HandleResult(new SparqlResult())) ParserHelper.Stop();
                                continue;
                            }

                            //Get the values of each Binding
                            String var;
                            INode value;
                            SparqlResult result = new SparqlResult();
                            while (context.Input.Read())
                            {
                                //Stop reading when we hit the </binding>
                                if (context.Input.NodeType == XmlNodeType.EndElement && context.Input.Name.Equals("result")) break;

                                //Must be a <binding> element
                                if (!context.Input.Name.Equals("binding"))
                                {
                                    throw new RdfParseException("Unable to Parse a SPARQL Result Set since a <result> element contains an unexpected element <" + context.Input.Name + ">!");
                                }

                                //Must have only 1 attribute
                                if (context.Input.AttributeCount != 1)
                                {
                                    throw new RdfParseException("Unable to Parse a SPARQL Result Set since a <binding> element has too few/many attributes, only a 'name' attribute should be present!");
                                }

                                //Get the Variable this is a binding for and its Value
                                context.Input.MoveToNextAttribute();
                                var = context.Input.Value;
                                if (!context.Input.Read()) throw new RdfParseException("Unable to Parse a SPARQL Result Set as reached the end of input when the contents of a <binding> element was expected");
                                value = this.ParseValue(context);

                                //Check that the Variable was defined in the Header
                                if (!context.Variables.Contains(var))
                                {
                                    throw new RdfParseException("Unable to Parse a SPARQL Result Set since a <binding> element attempts to bind a value to the variable '" + var + "' which is not defined in the <head> by a <variable> element!");
                                }

                                //Set the Variable to the Value
                                result.SetValue(var, value);
                            }

                            //Check that all Variables are bound for a given result binding nulls where appropriate
                            foreach (String v in context.Variables)
                            {
                                if (!result.HasValue(v))
                                {
                                    result.SetValue(v, null);
                                }
                            }

                            if (!context.Input.Name.Equals("result"))
                            {
                                throw new RdfParseException("Unable to Parse a SPARQL Result Set as reached the end of the input before a closing </result> element was found");
                            }

                            //Add to results set
                            if (!context.Handler.HandleResult(result)) ParserHelper.Stop();
                        }
                    }

                    if (!context.Input.Name.Equals("results"))
                    {
                        throw new RdfParseException("Unable to Parse a SPARQL Result Set as reached the end of the input before the closing </results> element was found");
                    }
                }
                else if (context.Input.Name.Equals("boolean"))
                {
                    //Can't be any <variable> elements
                    if (context.Variables.Count > 0)
                    {
                        throw new RdfParseException("Unable to Parse a SPARQL Result Set since the <boolean> element is specified but the <head> contained one/more <variable> elements which is not permitted!");
                    }

                    try
                    {
                        //Get the value of the <boolean> element as a Boolean
                        Boolean b = Boolean.Parse(context.Input.ReadInnerXml());
                        context.Handler.HandleBooleanResult(b);
                    }
                    catch (Exception)
                    {
                        throw new RdfParseException("Unable to Parse a SPARQL Result Set since the <boolean> element contained a value that could not be understood as a Boolean value!");
                    }
                }
                else
                {
                    throw new RdfParseException("Unable to Parse a SPARQL Result Set since the second Child Node of the <sparql> element is not the required <results> or <boolean> element!");
                }

                context.Handler.EndResults(true);
            }
            catch (RdfParsingTerminatedException)
            {
                context.Handler.EndResults(true);
            }
            catch
            {
                //Some other Error
                context.Handler.EndResults(false);
                throw;
            }
        }
コード例 #37
0
 private static bool CompareSolutions(SparqlResult x, SparqlResult y)
 {
     if (x.Variables.Count().Equals(y.Variables.Count()) &&
         x.Variables.All(xv=>y.Variables.Contains(xv)))
     {
         foreach (var xv in x.Variables)
         {
             var xb = x[xv];
             var yb = y[xv];
             if (!CompareNodes(xb, yb)) return false;
         }
         return true;
     }
     return false;
 }
コード例 #38
0
ファイル: KwSearch.cs プロジェクト: sherifkandeel/weet-it_WCF
        private static int scorecalc(string keyword, SparqlResult singleuri)
        {
            List<string> disambiguate_links = new List<string>();
            string check_disambig;
            int score_redirect = 0;
            int score_resource = 0;
            SparqlResultSet result;
            score_resource = computeLevenshteinDistance(keyword, singleuri.Value("literal").ToString().Replace("@en", ""));
            if (singleuri.Value("redirects") != null)
            {

                if (disambiguate_links.Contains(singleuri.Value("redirects").ToString()))
                    return 1000;
                check_disambig = "ASK where {<" + util.encodeURI(singleuri.Value("redirects").ToString()) + "> <http://dbpedia.org/ontology/wikiPageDisambiguates>    ?disamb                       }";
                result = Request.RequestWithHTTP(check_disambig);
                if (result.Result == true)
                {
                    disambiguate_links.Add(singleuri.Value("redirects").ToString());
                    return 1000;
                }

                string redirect_query = "select * where{ <" + singleuri.Value("redirects").ToString() + "><http://www.w3.org/2000/01/rdf-schema#label> ?redirect_label}";
                result = Request.RequestWithHTTP(redirect_query);
                if (result.Count != 0)
                {
                    score_redirect = computeLevenshteinDistance(keyword, result[0].Value("redirect_label").ToString().Replace("@en", ""));
                    return (score_redirect <= score_resource ? score_redirect : score_resource);
                }
                else
                {
                    return score_resource;
                }
            }
            return score_resource;
        }
コード例 #39
0
ファイル: SparqlTsvParser.cs プロジェクト: jmahmud/RDFer
        private void TryParseResultRow(TokenisingResultParserContext context)
        {
            IToken next = context.Tokens.Peek();
            if (next.TokenType == Token.EOF)
            {
                context.Tokens.Dequeue();
                return;
            }

            bool allowEOL = true, expectTab = false;
            int v = 0;
            SparqlResult result = new SparqlResult();
            while (true)
            {
                next = context.Tokens.Dequeue();
                switch (next.TokenType)
                {
                    case Token.URI:
                        if (expectTab) throw ParserHelper.Error("Unexpected URI, expected a Tab between RDF Terms", next);
                        if (v >= context.Variables.Count) throw ParserHelper.Error("Too many RDF Terms, only expecting " + context.Variables.Count + " terms", next);
                        INode uri = ParserHelper.TryResolveUri(context, next);
                        result.SetValue(context.Variables[v], uri);
                        v++;
                        allowEOL = true;
                        expectTab = true;
                        break;

                    case Token.BLANKNODEWITHID:
                        if (expectTab) throw ParserHelper.Error("Unexpected Blank Node, expected a Tab between RDF Terms", next);
                        if (v >= context.Variables.Count) throw ParserHelper.Error("Too many RDF Terms, only expecting " + context.Variables.Count + " terms", next);
                        INode blank = context.Handler.CreateBlankNode(next.Value.Substring(2));
                        result.SetValue(context.Variables[v], blank);
                        v++;
                        allowEOL = true;
                        expectTab = true;
                        break;

                    case Token.LITERAL:
                    case Token.LONGLITERAL:
                    case Token.PLAINLITERAL:
                        if (expectTab) throw ParserHelper.Error("Unexpected Blank Node, expected a Tab between RDF Terms", next);
                        if (v >= context.Variables.Count) throw ParserHelper.Error("Too many RDF Terms, only expecting " + context.Variables.Count + " terms", next);
                        INode lit = this.TryParseLiteral(context, next);
                        result.SetValue(context.Variables[v], lit);
                        v++;
                        allowEOL = true;
                        expectTab = true;
                        break;

                    case Token.EOL:
                        if (allowEOL)
                        {
                            break;
                        }
                        else
                        {
                            if (v == context.Variables.Count - 1)
                            {
                                //If this is the last expected term then this must be an empty term
                                v++;
                                break;
                            }
                            throw ParserHelper.Error("Unexpected End of Line, expected a RDF Term Token", next);
                        }

                    case Token.TAB:
                        if (!expectTab)
                        {
                            //This is an empty field
                            if (v >= context.Variables.Count) throw ParserHelper.Error("Too many RDF Terms, only expecting " + context.Variables.Count + " terms", next);
                            v++;
                        }
                        expectTab = false;
                        allowEOL = false;
                        break;

                    case Token.EOF:
                        if (!allowEOL) throw ParserHelper.Error("Unexpected EOF, expected another RDF Term for the Result Row", next);
                        break;

                    default:
                        throw ParserHelper.Error("Unexpected Token '" + next.GetType().ToString() + "' encountered", next);
                 }

                //Stop when we've hit the End of the Line/File
                if (next.TokenType == Token.EOL || next.TokenType == Token.EOF) break;
            }

            if (!context.Handler.HandleResult(result)) ParserHelper.Stop();
        }
コード例 #40
0
        /// <summary>
        /// Parser method which parses a Bound Variable Object which occurs within a Binding Object
        /// </summary>
        /// <param name="context">Parser Context</param>
        /// <param name="var">Variable Name</param>
        /// <param name="r">Result Object that is being constructed from the Binding Object</param>
        private void ParseBoundVariable(SparqlJsonParserContext context, String var, SparqlResult r)
        {
            String token, nodeValue, nodeType, nodeLang, nodeDatatype;
            nodeValue = nodeType = nodeLang = nodeDatatype = null;

            //Can we read the start of an Object
            if (context.Input.Read())
            {
                if (context.Input.TokenType == JsonToken.StartObject)
                {
                    context.Input.Read();

                    while (context.Input.TokenType != JsonToken.EndObject)
                    {
                        token = context.Input.Value.ToString().ToLower();

                        //Check that we get a Property Value as a String
                        context.Input.Read();
                        if (context.Input.TokenType != JsonToken.String)
                        {
                            throw Error(context, "Unexpected Token '" + context.Input.TokenType.ToString() + "' encountered, expected a Property Value describing one of the properties of an Variable Binding");
                        }

                        //Extract the Information from the Object
                        if (token.Equals("value"))
                        {
                            nodeValue = context.Input.Value.ToString();
                        }
                        else if (token.Equals("type"))
                        {
                            nodeType = context.Input.Value.ToString().ToLower();
                        }
                        else if (token.Equals("lang") || token.Equals("xml:lang"))
                        {
                            if (nodeLang == null && nodeDatatype == null)
                            {
                                nodeLang = context.Input.Value.ToString();
                            }
                            else
                            {
                                throw Error(context, "Unexpected Language Property specified for an Object Node where a Language or Datatype has already been specified");
                            }
                        }
                        else if (token.Equals("datatype"))
                        {
                            if (nodeDatatype == null && nodeLang == null)
                            {
                                nodeDatatype = context.Input.Value.ToString();
                            }
                            else
                            {
                                throw Error(context, "Unexpected Datatype Property specified for an Object Node where a Language or Datatype has already been specified");
                            }
                        }
                        else
                        {
                            throw Error(context, "Unexpected Property '" + token + "' specified for an Object Node, only 'value', 'type', 'lang' and 'datatype' are valid properties");
                        }

                        //Get Next Token
                        if (!context.Input.Read())
                        {
                            throw new RdfParseException("Unexpected End of Input while trying to parse a Bound Variable Object");
                        }
                    }

                    //Validate the Information
                    if (nodeType == null)
                    {
                        throw new RdfParseException("Cannot parse a Node from the JSON where no 'type' property was specified in the JSON Object representing the Node");
                    }
                    if (nodeValue == null)
                    {
                        throw new RdfParseException("Cannot parse a Node from the JSON where no 'value' property was specified in the JSON Object representing the Node");
                    }

                    //Turn this information into a Node
                    INode n;
                    if (nodeType.Equals("uri"))
                    {
                        n = context.Handler.CreateUriNode(new Uri(nodeValue));
                    }
                    else if (nodeType.Equals("bnode"))
                    {
                        if (nodeValue.StartsWith("_:"))
                        {
                            n = context.Handler.CreateBlankNode(nodeValue.Substring(2));
                        }
                        else if (nodeValue.Contains("://"))
                        {
                            n = context.Handler.CreateBlankNode(nodeValue.Substring(nodeValue.IndexOf("://") + 3));
                        }
                        else if (nodeValue.Contains(":"))
                        {
                            n = context.Handler.CreateBlankNode(nodeValue.Substring(nodeValue.LastIndexOf(':') + 1));
                        }
                        else
                        {
                            n = context.Handler.CreateBlankNode(nodeValue);
                        }
                    }
                    else if (nodeType.Equals("literal") || nodeType.Equals("typed-literal"))
                    {
                        if (nodeLang != null)
                        {
                            n = context.Handler.CreateLiteralNode(nodeValue, nodeLang);
                        }
                        else if (nodeDatatype != null)
                        {
                            n = context.Handler.CreateLiteralNode(nodeValue, new Uri(nodeDatatype));
                        }
                        else
                        {
                            n = context.Handler.CreateLiteralNode(nodeValue);
                        }
                    }
                    else
                    {
                        throw new RdfParseException("Cannot parse a Node from the JSON where the 'type' property has a value of '" + nodeType + "' which is not one of the permitted values 'uri', 'bnode', 'literal' or 'typed-literal' in the JSON Object representing the Node");
                    }

                    //Check that the Variable was defined in the Header
                    if (!context.Variables.Contains(var))
                    {
                        throw new RdfParseException("Unable to Parse a SPARQL Result Set since a Binding Object attempts to bind a value to the variable '" + var + "' which is not defined in the Header Object in the value for the 'vars' property!");
                    }

                    //Add to the result
                    r.SetValue(var, n);
                }
                else
                {
                    throw Error(context, "Unexpected Token '" + context.Input.TokenType.ToString() + "' encountered, expected the start of a Bound Variable Object");
                }
            }
            else
            {
                throw Error(context, "Unexpected End of Input while trying to parse a Bound Variable Object");
            }
        }
コード例 #41
0
 public MySparqlResult(SparqlResult sr)
 {
     Data.Set(sr);
 }
コード例 #42
0
        /// <summary>
        /// Extracts the corresponding value from the SemWeb results for a member access projection.
        /// </summary>
        /// <param name="vb">The SemWeb results.</param>
        /// <returns>the value that was extracted (and converted) from the results.</returns>
        private object ExtractMemberAccess(SparqlResult vb)
        {
            // work out if the SelectExpression really is a member access
            var ue = (SelectExpression).Arguments[1] as UnaryExpression;
            if (ue == null)
                throw new ArgumentException("incompatible expression type");
    
            var le = ue.Operand as LambdaExpression;
            if (le == null)
                throw new LinqToRdfException("Incompatible expression type found when building ontology projection");

            if (le.Body is MemberExpression)
            {
                // work out which member is being queried on
                var memberExpression = (MemberExpression) le.Body;
                MemberInfo memberInfo = memberExpression.Member;
                // get its name and use that as a key into the results
                //string vVal = vb[memberInfo.Name].ToString();
                // convert the result from XSDT format to .NET types
                if (!vb.HasValue(memberInfo.Name)) return null;
                var tc = new XsdtTypeConverter();
                return tc.Parse(vb[memberInfo.Name]);
                //return tc.Parse(vVal);
            }
            return null;
        }
コード例 #43
0
        /// <summary>
        /// stores the result from a SemWeb result into a <see cref="PropertyInfo"/> doing whatever conversions are required.
        /// </summary>
        /// <param name="semwebBindings">The incoming result from semweb.</param>
        /// <param name="obj">The object instance on wqhich the property is to be set</param>
        /// <param name="propertyInfo">The <see cref="PropertyInfo"/> identifying the property to be populated with the value stored in <see cref="semwebBindings"/>.</param>
        public static void PopulateProperty(SparqlResult semwebBindings, object obj, PropertyInfo propertyInfo)
        {
            if (semwebBindings.HasValue(propertyInfo.Name))
            {
                if (semwebBindings[propertyInfo.Name] == null) return;
                var tc = new XsdtTypeConverter();
                object x = tc.Parse(semwebBindings[propertyInfo.Name]);

                if (x is IConvertible)
                    propertyInfo.SetValue(obj, Convert.ChangeType(x, propertyInfo.PropertyType), null);
                else 
                    // if it's not convertible, it could be because the type is an MS XSDT type rather than a .NET primitive 
                    if (x.GetType().Namespace == "System.Runtime.Remoting.Metadata.W3cXsd2001")
                    {
                        switch (x.GetType().Name)
                        {
                            case "SoapDate":
                                var d = (SoapDate) x;
                                propertyInfo.SetValue(obj, Convert.ChangeType(d.Value, propertyInfo.PropertyType), null);
                                break;
                            default:
                                break;
                        }
                    }
                    else if (propertyInfo.PropertyType == typeof (string))
                    {
                        propertyInfo.SetValue(obj, x.ToString(), null);
                    }
            }
        }
コード例 #44
0
 private static bool CompareSolutions(SparqlResult x, SparqlResult y, Dictionary<string,string> bnodeMap)
 {
     var boundVarsX = x.Variables.Where(v=>x.HasValue(v) && x.Value(v)!=null);
     var boundVarsY = y.Variables.Where(v=>y.HasValue(v) && y.Value(v)!=null);
     if (!boundVarsX.Any() && !boundVarsY.Any()) return true;
     if (x.Variables.Count().Equals(y.Variables.Count()) &&
         x.Variables.All(xv=>y.Variables.Contains(xv)))
     {
         foreach (var xv in x.Variables)
         {
             var xb = x[xv];
             var yb = y[xv];
             if (!CompareNodes(xb, yb, bnodeMap)) return false;
         }
         return true;
     }
     return false;
 }
コード例 #45
0
ファイル: BaseHandler.cs プロジェクト: jbunzel/MvcRQ_git
 /// <summary>
 /// Handlers SPARQL Results
 /// </summary>
 /// <param name="result">Result</param>
 /// <returns></returns>
 public bool HandleResult(SparqlResult result)
 {
     if (!this._inUse) throw new RdfParseException("Cannot Handle a Result as this Handler is not currently in-use");
     return this.HandleResultInternal(result);
 }
コード例 #46
0
ファイル: BaseHandler.cs プロジェクト: jbunzel/MvcRQ_git
 /// <summary>
 /// Must be overridden by derived handlers to appropriately handler SPARQL Results
 /// </summary>
 /// <param name="result">Result</param>
 /// <returns></returns>
 protected abstract bool HandleResultInternal(SparqlResult result);
コード例 #47
0
        /// <summary>
        /// Assigns the instance URI from the SPARQL result bindings.
        /// </summary>
        /// <param name="obj">The object to assign the URI to.</param>
        /// <param name="queryAlias">The query alias that was used in LINQ and SPARQL.</param>
        /// <param name="semwebResult">The semweb result to take the value from.</param>
        private void AssignInstanceUri(OwlInstanceSupertype obj, string queryAlias,
                                                        SparqlResult result)
        {
            // if there is no alias, then there's no way to work out what contains the instance URI
            if (string.IsNullOrEmpty(queryAlias))
            {
                return;
            }

            // if there is a binding with the same name as the alias
            if (result.Variables.Contains(queryAlias))
            {
                // get string representation of the instance URI
                string uri = result[queryAlias].ToString();

                // is it enclosed in angle brackets? then strip them.
                if (uri.StartsWith("<") && uri.EndsWith(">"))
                {
                    uri = uri.Substring(1, uri.Length - 2);
                }

                // can this be parsed as a URI? if so then assign to instance URI property of obj
                if (Uri.IsWellFormedUriString(uri, UriKind.RelativeOrAbsolute))
                {
                    obj.InstanceUri = uri;
                }
            }
        }
コード例 #48
0
 /// <summary>
 /// Formats a SPARQL Result using this Formatter to format the Node values for each Variable
 /// </summary>
 /// <param name="result">SPARQL Result</param>
 /// <returns></returns>
 public virtual String Format(SparqlResult result)
 {
     return result.ToString(this);
 }
コード例 #49
0
        /// <summary>
        /// Parser method which parses a Binding Object which occurs in the array of Bindings
        /// </summary>
        private void ParseBinding(SparqlJsonParserContext context)
        {
            //Can we read some properties
            if (context.Input.Read())
            {
                SparqlResult result = new SparqlResult();
                while (context.Input.TokenType != JsonToken.EndObject)
                {
                    if (context.Input.TokenType == JsonToken.PropertyName)
                    {
                        //Each Property Name should be for a variable
                        this.ParseBoundVariable(context, context.Input.Value.ToString(), result);
                    }
                    else
                    {
                        throw Error(context, "Unexpected Token '" + context.Input.TokenType.ToString() + "' encountered, expected a Property Name giving the Binding for a Variable for this Result");
                    }

                    //Get Next Token
                    if (!context.Input.Read())
                    {
                        throw new RdfParseException("Unexpected End of Input while trying to parse a Binding Object");
                    }
                }

                //Check that all Variables are bound for a given result binding nulls where appropriate
                foreach (String v in context.Variables)
                {
                    if (!result.HasValue(v))
                    {
                        result.SetValue(v, null);
                    }
                }

                //Add to Results
                if (!context.Handler.HandleResult(result)) throw ParserHelper.Stop();
            }
            else
            {
                throw new RdfParseException("Unexpected End of Input while trying to parse a Binding Object");
            }
        }
コード例 #50
0
ファイル: SparqlRdfParser.cs プロジェクト: jbunzel/MvcRQ_git
        /// <summary>
        /// Internal method which actually parses the Result Set by traversing the RDF Graph appropriately
        /// </summary>
        /// <param name="context">Parser Context</param>
        private void Parse(SparqlRdfParserContext context)
        {
            try
            {
                context.Handler.StartResults();

                //Create relevant Nodes
                context.Graph.NamespaceMap.AddNamespace("rdf", new Uri(NamespaceMapper.RDF));
                context.Graph.NamespaceMap.AddNamespace("rs", new Uri(SparqlSpecsHelper.SparqlRdfResultsNamespace));
                IUriNode rdfType = context.Graph.CreateUriNode("rdf:type");
                IUriNode resultSetClass = context.Graph.CreateUriNode("rs:ResultSet");
                IUriNode resultVariable = context.Graph.CreateUriNode("rs:resultVariable");
                IUriNode solution = context.Graph.CreateUriNode("rs:solution");
                IUriNode binding = context.Graph.CreateUriNode("rs:binding");
                IUriNode value = context.Graph.CreateUriNode("rs:value");
                IUriNode variable = context.Graph.CreateUriNode("rs:variable");
                IUriNode boolean = context.Graph.CreateUriNode("rs:boolean");

                //Try to get a ResultSet object
                Triple rset = context.Graph.Triples.WithPredicateObject(rdfType, resultSetClass).FirstOrDefault();
                if (rset != null)
                {
                    INode rsetID = rset.Subject;

                    //Find the Variables the Result Set contains or the Boolean Value
                    List<Triple> temp = context.Graph.Triples.WithSubjectPredicate(rsetID, boolean).ToList();
                    if (temp.Count > 0)
                    {
                        if (temp.Count > 1) throw new RdfParseException("Result Set has more than one boolean result defined for it");

                        Triple booleanResult = temp.First();
                        INode result = booleanResult.Object;
                        if (result.NodeType == NodeType.Literal)
                        {
                            ILiteralNode lit = (ILiteralNode)result;
                            if (lit.DataType != null)
                            {
                                if (lit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeBoolean))
                                {
                                    bool b;
                                    if (Boolean.TryParse(lit.Value, out b))
                                    {
                                        context.Handler.HandleBooleanResult(b);
                                        return;
                                    }
                                    else
                                    {
                                        throw new RdfParseException("Result Set has a boolean result which is a Literal typed as boolean but which does not contain a valid boolean value");
                                    }
                                }
                                else
                                {
                                    throw new RdfParseException("Result Set has a boolean result which is a Literal which is not boolean typed");
                                }
                            }
                            else
                            {
                                throw new RdfParseException("Result Set has a boolean result which is a Literal which is not typed as a boolean");
                            }
                        }
                        else
                        {
                            throw new RdfParseException("Result Set has a boolean result which is not a Literal Node");
                        }
                    }
                    else
                    {
                        //We're expected one/more variables
                        temp = context.Graph.Triples.WithSubjectPredicate(rsetID, resultVariable).ToList();
                        if (temp.Count > 0)
                        {
                            foreach (Triple t in temp)
                            {
                                if (t.Object.NodeType == NodeType.Literal)
                                {
                                    if (!context.Handler.HandleVariable(((ILiteralNode)t.Object).Value)) ParserHelper.Stop();
                                    context.Variables.Add(((ILiteralNode)t.Object).Value);
                                }
                                else
                                {
                                    throw new RdfParseException("Result Set has a result variable definition which is not a Literal Node");
                                }
                            }
                        }
                        else
                        {
                            throw new RdfParseException("Result Set does not define any result variables or a boolean result");
                        }

                        //Then we're expecting some Solutions
                        temp = context.Graph.Triples.WithSubjectPredicate(rsetID, solution).ToList();
                        foreach (Triple slnTriple in temp)
                        {
                            //Each Solution has some Bindings
                            INode slnID = slnTriple.Object;
                            bool ok = false;
                            SparqlResult r = new SparqlResult();

                            foreach (Triple bindingTriple in context.Graph.Triples.WithSubjectPredicate(slnID, binding))
                            {
                                //Each Binding has a Variable and a Value
                                ok = true;
                                INode bindingID = bindingTriple.Object;
                                String var = String.Empty;
                                INode val = null;

                                //Retrieve the Variable and the Bound Value
                                foreach (Triple valueTriple in context.Graph.Triples.WithSubject(bindingID))
                                {
                                    if (valueTriple.Predicate.Equals(variable))
                                    {
                                        if (!var.Equals(String.Empty)) throw new RdfParseException("Result Set contains a Binding which refers to more than one Variable");
                                        if (valueTriple.Object.NodeType != NodeType.Literal) throw new RdfParseException("Result Set contains a Binding which refers to a Variable but not by a Literal Node as required");
                                        var = ((ILiteralNode)valueTriple.Object).Value;
                                    }
                                    else if (valueTriple.Predicate.Equals(value))
                                    {
                                        if (val != null) throw new RdfParseException("Result Set contains a Binding which has more than one Value");
                                        val = valueTriple.Object;
                                    }
                                }
                                if (var.Equals(String.Empty) || val == null) throw new RdfParseException("Result Set contains a Binding which doesn't contain both a Variable and a Value");

                                //Check that the Variable was defined in the Header
                                if (!context.Variables.Contains(var))
                                {
                                    throw new RdfParseException("Unable to Parse a SPARQL Result Set since a <binding> element attempts to bind a value to the variable '" + var + "' which is not defined in the <head> by a <variable> element!");
                                }

                                r.SetValue(var, val);
                            }
                            if (!ok) throw new RdfParseException("Result Set contains a Solution which has no Bindings");

                            //Check that all Variables are bound for a given result binding nulls where appropriate
                            foreach (String v in context.Variables)
                            {
                                if (!r.HasValue(v))
                                {
                                    r.SetValue(v, null);
                                }
                            }

                            if (!context.Handler.HandleResult(r)) ParserHelper.Stop();
                        }
                    }
                }
                else
                {
                    throw new RdfParseException("No Result Set object is defined in the Graph");
                }

                context.Handler.EndResults(true);
            }
            catch (RdfParsingTerminatedException)
            {
                context.Handler.EndResults(true);
            }
            catch
            {
                context.Handler.EndResults(false);
                throw;
            }
        }
コード例 #51
0
ファイル: MultisetHandler.cs プロジェクト: jmahmud/RDFer
 /// <summary>
 /// Handles a Result by adding it to the Multiset
 /// </summary>
 /// <param name="result">Result</param>
 /// <returns></returns>
 protected override bool HandleResultInternal(SparqlResult result)
 {
     this._mset.Add(new Set(result));
     return true;
 }
コード例 #52
0
ファイル: SparqlFormatter.cs プロジェクト: jmahmud/RDFer
 /// <summary>
 /// Formats a SPARQL Result using this Formatter to format the Node values for each Variable
 /// </summary>
 /// <param name="result">SPARQL Result</param>
 /// <returns></returns>
 public override String Format(SparqlResult result)
 {
     return result.ToString(this);
 }
コード例 #53
0
        /// <summary>
        /// Executes a SPARQL Query on the native Quad Store
        /// </summary>
        /// <param name="sparqlQuery">SPARQL Query to execute</param>
        /// <returns></returns>
        /// <remarks>
        /// <para>
        /// This method will first attempt to parse the query into a <see cref="SparqlQuery">SparqlQuery</see> object.  If this succeeds then the Query Type can be used to determine how to handle the response.
        /// </para>
        /// <para>
        /// If the parsing fails then the query will be executed anyway using Virtuoso's SPASQL (SPARQL + SQL) syntax.  Parsing can fail because Virtuoso supports various SPARQL extensions which the library does not support.  These include things like aggregate functions but also SPARQL Update statements.
        /// </para>
        /// <para>
        /// If you use an aggregate query which has an Integer, Decimal or Double type result then you will receive a <see cref="SparqlResultSet">SparqlResultSet</see> containing a single <see cref="SparqlResult">SparqlResult</see> which has contains a binding for a variable named <strong>Result</strong> which contains a <see cref="LiteralNode">LiteralNode</see> typed to the appropriate datatype.
        /// </para>
        /// </remarks>
        /// <exception cref="RdfQueryException">Thrown if an error occurs in making the query</exception>
        public Object Query(String sparqlQuery)
        {
            Object finalResult = null;
            DataTable results = new DataTable();
            results.Columns.CollectionChanged += new System.ComponentModel.CollectionChangeEventHandler(Columns_CollectionChanged);

            //See if the query can be parsed into a SparqlQuery object
            //It might not since the user might use Virtuoso's extensions to Sparql in their query
            try
            {
                //We'll set the Parser to SPARQL 1.1 mode even though Virtuoso's SPARQL implementation has
                //various perculiarties in their SPARQL 1.1 implementation and we'll try and 
                //handle the potential results in the catch branch if a valid SPARQL 1.0 query
                //cannot be parsed
                //Change made in response to a bug report by Aleksandr A. Zaripov [[email protected]]
                SparqlQueryParser parser = new SparqlQueryParser();
                parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_1;
                SparqlQuery query = parser.ParseFromString(sparqlQuery);

                switch (query.QueryType)
                {
                    case SparqlQueryType.Select:
                    case SparqlQueryType.SelectAll:
                    case SparqlQueryType.SelectAllDistinct:
                    case SparqlQueryType.SelectAllReduced:
                    case SparqlQueryType.SelectDistinct:
                    case SparqlQueryType.SelectReduced:
                        //Type the Tables columns as System.Object
                        foreach (SparqlVariable var in query.Variables)
                        {
                            if (var.IsResultVariable)
                            {
                                results.Columns.Add(var.Name, typeof(System.Object));
                            }
                        }
                        break;
                }

                try 
                {
                    this.Open(false);

                    //Make the Query against Virtuoso
                    VirtuosoCommand cmd = this._db.CreateCommand();
                    cmd.CommandText = "SPARQL " + sparqlQuery;
                    VirtuosoDataAdapter adapter = new VirtuosoDataAdapter(cmd);
                    adapter.Fill(results);

                    //Decide how to process the results based on the return type
                    switch (query.QueryType)
                    {
                        case SparqlQueryType.Ask:
                            //Expect a DataTable containing a single row and column which contains a boolean

                            if (results.Rows.Count == 1 && results.Columns.Count == 1)
                            {
                                bool result;
                                int r;
                                if (Boolean.TryParse(results.Rows[0][0].ToString(), out result))
                                {
                                    finalResult = new SparqlResultSet(result);
                                }
                                else if (Int32.TryParse(results.Rows[0][0].ToString(), out r))
                                {
                                    if (r == 1)
                                    {
                                        finalResult = new SparqlResultSet(true);
                                    }
                                    else
                                    {
                                        finalResult = new SparqlResultSet(false);
                                    }
                                }
                                else
                                {
                                    throw new RdfQueryException("Expected a Boolean as the result of an ASK query but the non-boolean value '" + results.Rows[0][0].ToString() + "' was received");
                                }
                            }
                            else
                            {
                                //If we get anything else then we'll return that the result was False
                                finalResult = new SparqlResultSet(false);
                            }

                            break;
                        case SparqlQueryType.Construct:
                        case SparqlQueryType.Describe:
                        case SparqlQueryType.DescribeAll:
                            //Expect a DataTable containing a single row and column which contains a String
                            //That string will be a Turtle serialization of the Graph

                            if (results.Rows.Count == 1 && results.Columns.Count == 1)
                            {
                                try
                                {
                                    //Use StringParser to parse
                                    String data = results.Rows[0][0].ToString();
                                    TurtleParser ttlparser = new TurtleParser();
                                    Graph g = new Graph();
                                    StringParser.Parse(g, data, ttlparser);

                                    finalResult = g;
                                }
                                catch (RdfParseException parseEx)
                                {
                                    throw new RdfQueryException("Expected a valid Turtle serialization of the Graph resulting from a CONSTRUCT/DESCRIBE query but the result failed to parse", parseEx);
                                }
                            }
                            else
                            {
                                throw new RdfQueryException("Expected a single string value representing the serialization of the Graph resulting from a CONSTRUCT/DESCRIBE query but this was not received");
                            }

                            break;
                        case SparqlQueryType.Select:
                        case SparqlQueryType.SelectAll:
                        case SparqlQueryType.SelectAllDistinct:
                        case SparqlQueryType.SelectAllReduced:
                        case SparqlQueryType.SelectDistinct:
                        case SparqlQueryType.SelectReduced:
                            //Expect a DataTable containing columns for each Result Variable and a row for each solution
                            SparqlResultSet rset = new SparqlResultSet();
                            rset.SetResult(true);

                            //Get Result Variables
                            List<SparqlVariable> resultVars = query.Variables.Where(v => v.IsResultVariable).ToList();
                            foreach (SparqlVariable var in resultVars)
                            {
                                rset.AddVariable(var.Name);
                            }
                            Graph temp = new Graph();

                            //Convert each solution into a SPARQLResult
                            foreach (DataRow r in results.Rows)
                            {
                                SparqlResult result = new SparqlResult();
                                foreach (SparqlVariable var in resultVars)
                                {
                                    if (r[var.Name] != null)
                                    {
                                        result.SetValue(var.Name, this.LoadNode(temp, r[var.Name]));
                                    }
                                }
                                rset.AddResult(result);
                            }

                            finalResult = rset;

                            break;
                        default:
                            throw new RdfQueryException("Unable to process the Results of an Unknown query type");
                    }

                    this.Close(false);
                } 
                catch
                {
                    this.Close(true, true);
                    throw;
                }
            }
            catch (RdfParseException)
            {
                //Unable to parse a SPARQL 1.0 query
                //Have to attempt to detect the return type based on the DataTable that
                //the SPASQL (Sparql+SQL) query gives back

                //Make the Query against Virtuoso
                VirtuosoCommand cmd = this._db.CreateCommand();
                cmd.CommandText = "SPARQL " /*define output:format '_JAVA_' "*/ + sparqlQuery;
                VirtuosoDataAdapter adapter = new VirtuosoDataAdapter(cmd);
                adapter.Fill(results);

                //Try to detect the return type based on the DataTable configuration
                if (results.Rows.Count == 0 && results.Columns.Count > 0)
                {
                    //No Rows but some columns implies empty SELECT results
                    SparqlResultSet rset = new SparqlResultSet();
                    foreach (DataColumn col in results.Columns)
                    {
                        rset.AddVariable(col.ColumnName);
                    }

                    finalResult = rset;
                }
                else if (results.Rows.Count == 1 && results.Columns.Count == 1 && !Regex.IsMatch(sparqlQuery, "SELECT", RegexOptions.IgnoreCase))
                {
                    //Added a fix here suggested by Alexander Sidorov - not entirely happy with this fix as what happens if SELECT just happens to occur in a URI/Variable Name?

                    //Single Row and Column implies ASK/DESCRIBE/CONSTRUCT results
                    bool result;
                    int r;
                    decimal rdec;
                    double rdbl;
                    float rflt;

                    if (results.Rows[0][0].ToString().Equals(String.Empty))
                    {
                        //Empty Results
                        finalResult = new SparqlResultSet();
                    }
                    else if (Boolean.TryParse(results.Rows[0][0].ToString(), out result))
                    {
                        //Parseable Boolean so ASK Results
                        finalResult = new SparqlResultSet(result);
                    }
                    else if (Int32.TryParse(results.Rows[0][0].ToString(), out r))
                    {
                        //Parseable Integer so Aggregate SELECT Query Results
                        SparqlResultSet rset = new SparqlResultSet();
                        rset.AddVariable("Result");
                        SparqlResult res = new SparqlResult();
                        res.SetValue("Result", new LiteralNode(null, r.ToString(), new Uri(XmlSpecsHelper.XmlSchemaDataTypeInteger)));
                        rset.AddResult(res);

                        finalResult = rset;
                    }
                    else if (Single.TryParse(results.Rows[0][0].ToString(), out rflt))
                    {
                        //Parseable Single so Aggregate SELECT Query Results
                        SparqlResultSet rset = new SparqlResultSet();
                        rset.AddVariable("Result");
                        SparqlResult res = new SparqlResult();
                        res.SetValue("Result", new LiteralNode(null, rflt.ToString(), new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)));
                        rset.AddResult(res);

                        finalResult = rset;
                    }
                    else if (Double.TryParse(results.Rows[0][0].ToString(), out rdbl))
                    {
                        //Parseable Double so Aggregate SELECT Query Results
                        SparqlResultSet rset = new SparqlResultSet();
                        rset.AddVariable("Result");
                        SparqlResult res = new SparqlResult();
                        res.SetValue("Result", new LiteralNode(null, rdbl.ToString(), new Uri(XmlSpecsHelper.XmlSchemaDataTypeDouble)));
                        rset.AddResult(res);

                        finalResult = rset;
                    }
                    else if (Decimal.TryParse(results.Rows[0][0].ToString(), out rdec))
                    {
                        //Parseable Decimal so Aggregate SELECT Query Results
                        SparqlResultSet rset = new SparqlResultSet();
                        rset.AddVariable("Result");
                        SparqlResult res = new SparqlResult();
                        res.SetValue("Result", new LiteralNode(null, rdec.ToString(), new Uri(XmlSpecsHelper.XmlSchemaDataTypeDecimal)));
                        rset.AddResult(res);

                        finalResult = rset;
                    }
                    else
                    {
                        //String so try and parse as Turtle
                        try
                        {
                            //Use StringParser to parse
                            String data = results.Rows[0][0].ToString();
                            TurtleParser ttlparser = new TurtleParser();
                            Graph g = new Graph();
                            StringParser.Parse(g, data, ttlparser);

                            finalResult = g;
                        }
                        catch (RdfParseException)
                        {
                            //If it failed to parse then it might be the result of one of the aggregate
                            //functions that Virtuoso extends Sparql with
                            Graph temp = new Graph();
                            SparqlResultSet rset = new SparqlResultSet();
                            rset.AddVariable(results.Columns[0].ColumnName);
                            SparqlResult res = new SparqlResult();
                            res.SetValue(results.Columns[0].ColumnName, this.LoadNode(temp, results.Rows[0][0]));
                            //Nothing was returned here previously - fix submitted by Aleksandr A. Zaripov [[email protected]]
                            rset.AddResult(res);
                            finalResult = rset;
                        }
                    }
                }
                else
                {
                    //Any other number of rows/columns we have to assume that it's normal SELECT results
                    //Changed in response to bug report by Aleksandr A. Zaripov [[email protected]]

                    //SELECT Query Results
                    SparqlResultSet rset = new SparqlResultSet();
                    rset.SetResult(true);

                    //Get Result Variables
                    foreach (DataColumn col in results.Columns)
                    {
                        rset.AddVariable(col.ColumnName);
                    }
                    Graph temp = new Graph();

                    //Convert each solution into a SPARQLResult
                    foreach (DataRow r in results.Rows)
                    {
                        SparqlResult result = new SparqlResult();
                        foreach (String var in rset.Variables)
                        {
                            if (r[var] != null)
                            {
                                result.SetValue(var, this.LoadNode(temp, r[var]));
                            }
                        }
                        rset.AddResult(result);
                    }

                    finalResult = rset;
                }
            }

            return finalResult;
        }
コード例 #54
0
ファイル: WriteThroughHandler.cs プロジェクト: jmahmud/RDFer
 /// <summary>
 /// Writes a Result to the output
 /// </summary>
 /// <param name="result">SPARQL Result</param>
 /// <returns></returns>
 protected override bool HandleResultInternal(SparqlResult result)
 {
     if (this._currentType == SparqlResultsType.Boolean) throw new RdfParseException("Cannot handle a Result when the handler has already handled a boolean result");
     this._currentType = SparqlResultsType.VariableBindings;
     if (!this._headerWritten && this._formatter is IResultSetFormatter)
     {
         this._writer.WriteLine(((IResultSetFormatter)this._formatter).FormatResultSetHeader(this._currVariables.Distinct()));
         this._headerWritten = true;
     }
     this._writer.WriteLine(this._formatter.Format(result));
     return true;
 }
コード例 #55
0
ファイル: ResSetToJSON.cs プロジェクト: AliHosny/weet-it
 private static List<string> valuesOfResults(SparqlResult sq)
 {
     List<string> variableName = new List<string>();
     variableName = sq.Variables.ToList();
     List<string> output = new List<string>();
     foreach (string var in variableName)
     {
         output.Add(sq.Value(var).ToString());
     }
     return output;
 }
コード例 #56
0
ファイル: kwsearch.cs プロジェクト: AliHosny/weet-it
 private static int scorecalc(string keyword ,SparqlResult singleuri)
 {
     int score_redirect=0;
       int score_resource = 0;
        score_resource= computeLevenshteinDistance(keyword, singleuri.Value("literal").ToString());
        if (singleuri.Value("redirects") != null)
        {
        string disamb_query = "select * where{ <" + singleuri.Value("redirects").ToString() + "><http://www.w3.org/2000/01/rdf-schema#label> ?redirect_label}";
        SparqlResultSet result = remoteEndPoint.QueryWithResultSet(disamb_query);
        if (result.Count != 0)
        {
            score_redirect = computeLevenshteinDistance(keyword, result[0].Value("redirect_label").ToString());
          return(  score_redirect<score_resource? score_redirect: score_resource);
        }
        else
        {
            return score_resource;
        }
        }
        return score_resource;
 }
コード例 #57
0
ファイル: ResSetToJSON.cs プロジェクト: AliHosny/weet-it
        /// <summary>
        /// we get the values of each result from here
        /// </summary>
        /// <param name="sq">input sparqlResult</param>
        /// <returns>list of string of all the urls according to the query structure ex:?pf ?middle ?os ?ps </returns>
        private static List<string> valuesOfResults(SparqlResult sq)
        {
            //I need this one to know the variables names
            variableName = new List<string>();

            //List<string> variableName = new List<string>();
            variableName = sq.Variables.ToList();
            List<string> output = new List<string>();
            foreach (string var in variableName)
            {
                output.Add(sq.Value(var).ToString());
            }
            return output;
        }
コード例 #58
0
ファイル: ResultCountHandler.cs プロジェクト: jmahmud/RDFer
 /// <summary>
 /// Handles a SPARQL Result by incrementing the counter
 /// </summary>
 /// <param name="result">Result</param>
 /// <returns></returns>
 protected override bool HandleResultInternal(SparqlResult result)
 {
     this._counter++;
     return true;
 }
コード例 #59
0
ファイル: SparqlCsvParser.cs プロジェクト: jmahmud/RDFer
        private void TryParseResultRow(TokenisingResultParserContext context)
        {
            IToken next = context.Tokens.Peek();
            if (next.TokenType == Token.EOF)
            {
                context.Tokens.Dequeue();
                return;
            }

            bool allowEOL = true, expectComma = false;
            int v = 0;
            SparqlResult result = new SparqlResult();
            while (true)
            {
                next = context.Tokens.Dequeue();
                switch (next.TokenType)
                {

                    case Token.BLANKNODEWITHID:
                        if (expectComma) throw ParserHelper.Error("Unexpected Blank Node, expected a comma between RDF Terms", next);
                        if (v >= context.Variables.Count) throw ParserHelper.Error("Too many RDF Terms, only expecting " + context.Variables.Count + " terms", next);
                        INode blank = context.Handler.CreateBlankNode(next.Value.Substring(2));
                        result.SetValue(context.Variables[v], blank);
                        v++;
                        allowEOL = true;
                        expectComma = true;
                        break;

                    case Token.LITERAL:
                    case Token.PLAINLITERAL:
                        if (expectComma) throw ParserHelper.Error("Unexpected Blank Node, expected a comma between RDF Terms", next);
                        if (v >= context.Variables.Count) throw ParserHelper.Error("Too many RDF Terms, only expecting " + context.Variables.Count + " terms", next);

                        //Try and guess what kind of term this is
                        String lexicalForm = next.Value;
                        INode value;
                        if (lexicalForm.StartsWith("http://") || lexicalForm.StartsWith("https://") || lexicalForm.StartsWith("mailto:") || lexicalForm.StartsWith("ftp://"))
                        {
                            try
                            {
                                //Guessing a URI if starts with common URI prefix
                                value = context.Handler.CreateUriNode(UriFactory.Create(lexicalForm));
                            }
                            catch
                            {
                                //If invalid URI fall back to treating as literal
                                value = context.Handler.CreateLiteralNode(lexicalForm);
                            }
                        }
                        else
                        {
                            value = context.Handler.CreateLiteralNode(lexicalForm);
                        }

                        result.SetValue(context.Variables[v], value);
                        v++;
                        allowEOL = true;
                        expectComma = true;
                        break;

                    case Token.EOL:
                        if (allowEOL)
                        {
                            break;
                        }
                        else
                        {
                            if (v == context.Variables.Count - 1)
                            {
                                //If this is the last expected term then this must be an empty term
                                v++;
                                break;
                            }
                            throw ParserHelper.Error("Unexpected End of Line, expected a RDF Term Token", next);
                        }

                    case Token.COMMA:
                        if (!expectComma)
                        {
                            //This is an empty field
                            if (v >= context.Variables.Count) throw ParserHelper.Error("Too many RDF Terms, only expecting " + context.Variables.Count + " terms", next);
                            v++;
                        }
                        expectComma = false;
                        allowEOL = false;
                        break;

                    case Token.EOF:
                        if (!allowEOL) throw ParserHelper.Error("Unexpected EOF, expected another RDF Term for the Result Row", next);
                        break;

                    default:
                        throw ParserHelper.Error("Unexpected Token '" + next.GetType().ToString() + "' encountered", next);
                 }

                //Stop when we've hit the End of the Line/File
                if (next.TokenType == Token.EOL || next.TokenType == Token.EOF) break;
            }

            if (!context.Handler.HandleResult(result)) ParserHelper.Stop();
        }
コード例 #60
0
ファイル: ILinqResultsSink.cs プロジェクト: jbunzel/MvcRQ_git
 protected abstract void ProcessResult(SparqlResult result);