Ejemplo n.º 1
0
        public void ExecuteQuery()
        {
            ArrayList solutions = new ArrayList();

            if (SolutionIsPossible)
            {
                MySqlDataReader dataReader = null;
                try {
                    dataReader = itsTriples.ExecuteSqlQuery(itsQuerySql);
                    while (dataReader.Read())
                    {
                        QuerySolution solution = new QuerySolution();
                        int           col      = 0;
                        foreach (Variable var in itsSelectedVariables)
                        {
                            object resourceHash = dataReader.GetValue(col);
                            if (!resourceHash.Equals(DBNull.Value))
                            {
                                Resource resource = new Resource(Convert.ToInt32(resourceHash));
                                solution[var.Name] = resource;

                                int    nodeHash     = dataReader.GetInt32(col + 1);
                                char   nodeType     = dataReader.GetChar(col + 2);
                                string lexicalValue = dataReader.GetString(col + 3);
                                object rawSubValue  = dataReader.GetValue(col + 4);
                                string subValue     = null;
                                if (!rawSubValue.Equals(DBNull.Value))
                                {
                                    subValue = (string)rawSubValue;
                                }

                                GraphMember node = null;
                                switch (nodeType)
                                {
                                case 'u':
                                    node = new UriRef(lexicalValue);
                                    break;

                                case 'b':
                                    node = new BlankNode(nodeHash);
                                    break;

                                case 'p':
                                    node = new PlainLiteral(lexicalValue, subValue);
                                    break;

                                case 't':
                                    node = new TypedLiteral(lexicalValue, subValue);
                                    break;
                                }

                                solution.SetNode(var.Name, node);
                            }
                            col += 5;
                        }
                        solutions.Add(solution);
                    }
                }
                catch (MySqlException e) {
                    throw new ApplicationException("Error executing '" + itsQuerySql + "' for query " + itsQuery, e);
                }
                finally {
                    if (null != dataReader)
                    {
                        dataReader.Close();
                    }
                }
            }

            itsSolutions = solutions.GetEnumerator();
        }
Ejemplo n.º 2
0
 /// <summary>New blank labeled node subject.</summary>
 public static SubjectBuilder ForBlank(this GraphBuilder self, ReadOnlySpan <char> label, out BlankNode node)
 {
     node = self.Rdf().Blank(self.GraphId(), label);
     return(self.For(node));
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets the list of Search Results which match the given search term
        /// </summary>
        /// <param name="text">Search Term</param>
        /// <returns>A list of Search Results representing Nodes in the Knowledge Base that match the search term</returns>
        public List <SearchServiceResult> Search(String text)
        {
            String search = this._searchUri + "?search=" + Uri.EscapeDataString(text);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search);

            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = "text/json";

#if DEBUG
            if (Options.HttpDebugging)
            {
                Tools.HttpDebugRequest(request);
            }
#endif

            String jsonText;
            JArray json;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
#if DEBUG
                if (Options.HttpDebugging)
                {
                    Tools.HttpDebugResponse(response);
                }
#endif
                jsonText = new StreamReader(response.GetResponseStream()).ReadToEnd();
                json     = JArray.Parse(jsonText);

                response.Close();
            }

            //Parse the Response into Search Results
            try
            {
                List <SearchServiceResult> results = new List <SearchServiceResult>();

                foreach (JToken result in json.Children())
                {
                    JToken hit  = result.SelectToken("hit");
                    String type = (String)hit.SelectToken("type");
                    INode  node;
                    if (type.ToLower().Equals("uri"))
                    {
                        node = new UriNode(null, new Uri((String)hit.SelectToken("value")));
                    }
                    else
                    {
                        node = new BlankNode(null, (String)hit.SelectToken("value"));
                    }
                    double score = (double)result.SelectToken("score");

                    results.Add(new SearchServiceResult(node, score));
                }

                return(results);
            }
            catch (WebException webEx)
            {
#if DEBUG
                if (Options.HttpDebugging)
                {
                    if (webEx.Response != null)
                    {
                        Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                    }
                }
#endif
                throw new RdfReasoningException("A HTTP error occurred while communicating with Pellet Server", webEx);
            }
            catch (Exception ex)
            {
                throw new RdfReasoningException("Error occurred while parsing Search Results from the Search Service", ex);
            }
        }
Ejemplo n.º 4
0
        /**
         * Splits the hashgraph into multiple where each
         * graph represents all triples for each set of connected blank nodes
         * (blank nodes appearing in the same triple).
         *
         * Ground triples are removed (if previously present).
         *
         * Shallow copy: colours are preserved.
         *
         * @return
         */
        public ICollection <HashGraph> BlankNodePartition()
        {
            var part = new Partition <Node>();

            // first create a partition of blank nodes based
            // on being connected
            foreach (Triple t in _data)
            {
                if (t.Subject.IsBlankNode() && t.Object.IsBlankNode() && !t.Subject.Equals(t.Object))
                {
                    part.AddPair(t.Subject as Node, t.Object as Node);
                }
            }

            var pivotToGraph = new Dictionary <Node, HashGraph>();

            foreach (var t in _data)
            {
                // doesn't matter which we pick, both are in the
                // same partition
                BlankNode b = null;
                if (t.Subject.IsBlankNode())
                {
                    b = t.Subject.AsBlankNode();
                }
                else if (t.Object.IsBlankNode())
                {
                    b = t.Object.AsBlankNode();
                }
                else
                {
                    continue;
                }

                // use the lowest bnode in the partition
                // to map to its graph
                var  bp    = part.GetPartition(b);
                Node pivot = null;

                if (bp == null || bp.Count == 0)
                {
                    pivot = b; // singleton ... unconnected blank node
                }
                else
                {
                    pivot = bp[0];
                }

                HashGraph hg;
                if (!pivotToGraph.ContainsKey(pivot))
                {
                    hg = new HashGraph(_hf);
                    pivotToGraph.Add(pivot, hg);
                }
                else
                {
                    hg = pivotToGraph[pivot];
                }
                hg.AddTriple(t);
            }
            return(pivotToGraph.Values);
        }
Ejemplo n.º 5
0
 /// <summary>New blank labeled node subject.</summary>
 public static SubjectBuilder ForBlank(this GraphBuilder self, string label, out BlankNode node)
 {
     node = self.Rdf().Blank(self.GraphId(), label);
     return(self.For(node));
 }
Ejemplo n.º 6
0
 /**
  * Get the HashNode containing the current hash for the blank node.
  *
  * @param n
  * @return
  */
 public string GetHash(BlankNode n)
 {
     _dynamicHashes.TryGetValue(n, out string val);
     return(val);
 }
 private BlankNode NormalizeBlankNode(Dictionary <string, List <Triple> > tripleList, BlankNode bNode, string emptyListName)
 {
     if (tripleList.ContainsKey(bNode.ValueAsString()))
     {
         var hashSum = new byte[_hashCalculator.HashSize / 8];
         foreach (var ot in tripleList[bNode.ValueAsString()])
         {
             hashSum = ByteArrayUtils.AddHashes(hashSum, SimpleHash(ot));
         }
         return(new BlankNode(hashSum.ToHexString()));
     }
     else
     {
         return(new BlankNode(emptyListName));
     }
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets the list of Search Results which match the given search term.
        /// </summary>
        /// <param name="text">Search Term.</param>
        /// <param name="callback">Callback to invoke when the operation completes.</param>
        /// <param name="state">State to pass to the callback.</param>
        /// <remarks>
        /// If the operation succeeds the callback will be invoked normally, if there is an error the callback will be invoked with a instance of <see cref="AsyncError"/> passed as the state which provides access to the error message and the original state passed in.
        /// </remarks>
        public void Search(String text, PelletSearchServiceCallback callback, Object state)
        {
            String search = _searchUri + "?search=" + HttpUtility.UrlEncode(text);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search);

            request.Method = Endpoint.HttpMethods.First();
            request.Accept = "text/json";

            Tools.HttpDebugRequest(request);

            try
            {
                String jsonText;
                JArray json;
                request.BeginGetResponse(result =>
                {
                    try
                    {
                        using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                        {
                            Tools.HttpDebugResponse(response);
                            jsonText = new StreamReader(response.GetResponseStream()).ReadToEnd();
                            json     = JArray.Parse(jsonText);

                            response.Close();

                            // Parse the Response into Search Results

                            List <SearchServiceResult> results = new List <SearchServiceResult>();

                            foreach (JToken res in json.Children())
                            {
                                JToken hit  = res.SelectToken("hit");
                                String type = (String)hit.SelectToken("type");
                                INode node;
                                if (type.ToLower().Equals("uri"))
                                {
                                    node = new UriNode(null, UriFactory.Create((String)hit.SelectToken("value")));
                                }
                                else
                                {
                                    node = new BlankNode(null, (String)hit.SelectToken("value"));
                                }
                                double score = (double)res.SelectToken("score");

                                results.Add(new SearchServiceResult(node, score));
                            }

                            callback(results, state);
                        }
                    }
                    catch (WebException webEx)
                    {
                        if (webEx.Response != null)
                        {
                            Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                        }
                        callback(null, new AsyncError(new RdfReasoningException("A HTTP error occurred while communicating with the Pellet Server, see inner exception for details", webEx), state));
                    }
                    catch (Exception ex)
                    {
                        callback(null, new AsyncError(new RdfReasoningException("An unexpected error occurred while communicating with the Pellet Server, see inner exception for details", ex), state));
                    }
                }, null);
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null)
                {
                    Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                }
                callback(null, new AsyncError(new RdfReasoningException("A HTTP error occurred while communicating with the Pellet Server, see inner exception for details", webEx), state));
            }
            catch (Exception ex)
            {
                callback(null, new AsyncError(new RdfReasoningException("An unexpected error occurred while communicating with the Pellet Server, see inner exception for details", ex), state));
            }
        }
Ejemplo n.º 9
0
        private Uri TryParseContext(ITokenQueue tokens)
        {
            IToken next = tokens.Dequeue();

            if (next.TokenType == Token.DOT)
            {
                return(null);
            }
            else
            {
                INode context;
                switch (next.TokenType)
                {
                case Token.BLANKNODEWITHID:
                    context = new BlankNode(null, next.Value.Substring(2));
                    break;

                case Token.URI:
                    context = new UriNode(null, UriFactory.Create(next.Value));
                    break;

                case Token.LITERAL:
                    //Check for Datatype/Language
                    IToken temp = tokens.Peek();
                    if (temp.TokenType == Token.LANGSPEC)
                    {
                        tokens.Dequeue();
                        context = new LiteralNode(null, next.Value, temp.Value);
                    }
                    else if (temp.TokenType == Token.DATATYPE)
                    {
                        tokens.Dequeue();
                        context = new LiteralNode(null, next.Value, UriFactory.Create(temp.Value.Substring(1, temp.Value.Length - 2)));
                    }
                    else
                    {
                        context = new LiteralNode(null, next.Value);
                    }
                    break;

                default:
                    throw ParserHelper.Error("Unexpected Token '" + next.GetType().ToString() + "' encountered, expected a Blank Node/Literal/URI as the Context of the Triple", next);
                }

                //Ensure we then see a . to terminate the Quad
                next = tokens.Dequeue();
                if (next.TokenType != Token.DOT)
                {
                    throw ParserHelper.Error("Unexpected Token '" + next.GetType().ToString() + "' encountered, expected a Dot Token (Line Terminator) to terminate a Triple", next);
                }

                //Finally return the Context URI
                if (context.NodeType == NodeType.Uri)
                {
                    return(((IUriNode)context).Uri);
                }
                else if (context.NodeType == NodeType.Blank)
                {
                    return(UriFactory.Create("nquads:bnode:" + context.GetHashCode()));
                }
                else if (context.NodeType == NodeType.Literal)
                {
                    return(UriFactory.Create("nquads:literal:" + context.GetHashCode()));
                }
                else
                {
                    throw ParserHelper.Error("Cannot turn a Node of type '" + context.GetType().ToString() + "' into a Context URI for a Triple", next);
                }
            }
        }
Ejemplo n.º 10
0
 public override void Visit(BlankNode node)
 {
     SetCurrentNodeAsResult(node);
 }