Ejemplo n.º 1
0
        /// <summary>
        /// Makes a SPARQL Query against the Knowledge Base
        /// </summary>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <returns></returns>
        public Object Query(String sparqlQuery)
        {
            SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(UriFactory.Create(this._sparqlUri));

            using (HttpWebResponse response = endpoint.QueryRaw(sparqlQuery))
            {
                try
                {
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph      g      = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    return(g);
                }
                catch (RdfParserSelectionException)
                {
                    ISparqlResultsReader sparqlParser = MimeTypesHelper.GetSparqlParser(response.ContentType);
                    SparqlResultSet      results      = new SparqlResultSet();
                    sparqlParser.Load(results, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    return(results);
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the Raw Predictions Graph from the Knowledge Base
        /// </summary>
        /// <param name="individual">QName of an Individual</param>
        /// <param name="property">QName of a Property</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        public void PredictRaw(String individual, String property, GraphCallback callback, Object state)
        {
            String requestUri = this._predictUri + individual + "/" + property;

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

            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(this.MimeTypes.Where(t => !t.Equals("text/json")), MimeTypesHelper.SupportedRdfMimeTypes);

            Tools.HttpDebugRequest(request);

            request.BeginGetResponse(result =>
            {
                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                {
                    Tools.HttpDebugResponse(response);

                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph g           = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    callback(g, state);
                }
            }, null);
        }
Ejemplo n.º 3
0
        public void ServiceDescriptionOptionsRequestOnSparqlServer4()
        {
            EnsureIIS();
            String server = TestConfigManager.GetSetting(TestConfigManager.LocalGraphStoreUpdateUri);

            Console.WriteLine("Making an OPTIONS request to the web demos SPARQL Server Update Endpoint at " + server);
            Console.WriteLine();

            NTriplesFormatter formatter = new NTriplesFormatter();

            HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(server);

            request.Method = "OPTIONS";
            request.Accept = MimeTypesHelper.HttpAcceptHeader;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                Graph      g      = new Graph();
                parser.Load(g, new StreamReader(response.GetResponseStream()));

                TestTools.ShowGraph(g);

                Assert.False(g.IsEmpty, "A non-empty Service Description Graph should have been returned");

                response.Close();
            }
        }
Ejemplo n.º 4
0
        public void ServiceDescriptionOptionsRequestOnSparqlServer2()
        {
            EnsureIIS();
            String path = TestConfigManager.GetSetting(TestConfigManager.LocalGraphStoreUri) + "some/long/path/elsewhere";

            Console.WriteLine("Making an OPTIONS request to the web demos SPARQL Server at " + path);
            Console.WriteLine("This Test tries to ensure that the URI resolution works correctly");
            Console.WriteLine();

            NTriplesFormatter formatter = new NTriplesFormatter();

            HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(path);

            request.Method = "OPTIONS";
            request.Accept = MimeTypesHelper.HttpAcceptHeader;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                Graph      g      = new Graph();
                parser.Load(g, new StreamReader(response.GetResponseStream()));

                TestTools.ShowGraph(g);

                Assert.False(g.IsEmpty, "A non-empty Service Description Graph should have been returned");

                response.Close();
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Makes a SPARQL Query against the underlying 4store Instance processing the results with the appropriate handler from those provided
        /// </summary>
        /// <param name="rdfHandler">RDF Handler</param>
        /// <param name="resultsHandler">Results Handler</param>
        /// <param name="sparqlQuery">SPARQL Query</param>
        public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery)
        {
            try
            {
                //Ensure Proxy Settings have been taken from the class
                this._endpoint.Proxy = this.Proxy;
                this._endpoint.UseCredentialsForProxy = false;

                HttpWebResponse response = this._endpoint.QueryRaw(sparqlQuery);
                StreamReader    data     = new StreamReader(response.GetResponseStream());
                try
                {
                    //Is the Content Type referring to a Sparql Result Set format?
                    ISparqlResultsReader resreader = MimeTypesHelper.GetSparqlParser(response.ContentType);
                    resreader.Load(resultsHandler, data);
                    response.Close();
                }
                catch (RdfParserSelectionException)
                {
                    //If we get a Parser Selection exception then the Content Type isn't valid for a Sparql Result Set

                    //Is the Content Type referring to a RDF format?
                    IRdfReader rdfreader = MimeTypesHelper.GetParser(response.ContentType);
                    rdfreader.Load(rdfHandler, data);
                    response.Close();
                }
            }
            catch (WebException webEx)
            {
                throw StorageHelper.HandleHttpQueryError(webEx);
            }
        }
        /// <summary>
        /// Gets the raw Similarity Graph for the Knowledge Base.
        /// </summary>
        /// <param name="number">Number of Similar Individuals.</param>
        /// <param name="individual">QName of a Individual to find Similar Individuals to.</param>
        /// <returns></returns>
        public IGraph SimilarityRaw(int number, String individual)
        {
            if (number < 1)
            {
                throw new RdfReasoningException("Pellet Server requires the number of Similar Individuals to be at least 1");
            }

            String requestUri = _similarityUri + number + "/" + individual;

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

            request.Method = Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(MimeTypes.Where(t => !t.Equals("text/json")), MimeTypesHelper.SupportedRdfMimeTypes);

            Tools.HttpDebugRequest(request);

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                Tools.HttpDebugResponse(response);
                IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                Graph      g      = new Graph();
                parser.Load(g, new StreamReader(response.GetResponseStream()));

                response.Close();
                return(g);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Gets a Graph explaining the result of the SPARQL Query.
        /// </summary>
        /// <param name="sparqlQuery">SPARQL Query.</param>
        /// <returns></returns>
        public IGraph Explain(String sparqlQuery)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_explainUri + "?query=" + HttpUtility.UrlEncode(sparqlQuery));

            request.Method = Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(MimeTypes, MimeTypesHelper.SupportedRdfMimeTypes);

            Tools.HttpDebugRequest(request);

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Tools.HttpDebugResponse(response);
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph      g      = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    return(g);
                }
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null)
                {
                    Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                }
                throw new RdfReasoningException("A HTTP error occurred while communicating with the Pellet Server", webEx);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Makes a Query against the SPARQL Endpoint processing the results with an appropriate handler from those provided
        /// </summary>
        /// <param name="rdfHandler">RDF Handler</param>
        /// <param name="resultsHandler">Results Handler</param>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <returns></returns>
        public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery)
        {
            if (!this._skipLocalParsing)
            {
                //Parse the query locally to validate it and so we can decide what to do
                //when we receive the Response more easily as we'll know the query type
                //This also saves us wasting a HttpWebRequest on a malformed query
                SparqlQueryParser qparser = new SparqlQueryParser();
                SparqlQuery       q       = qparser.ParseFromString(sparqlQuery);

                switch (q.QueryType)
                {
                case SparqlQueryType.Ask:
                case SparqlQueryType.Select:
                case SparqlQueryType.SelectAll:
                case SparqlQueryType.SelectAllDistinct:
                case SparqlQueryType.SelectAllReduced:
                case SparqlQueryType.SelectDistinct:
                case SparqlQueryType.SelectReduced:
                    //Some kind of Sparql Result Set
                    this._endpoint.QueryWithResultSet(resultsHandler, sparqlQuery);
                    break;

                case SparqlQueryType.Construct:
                case SparqlQueryType.Describe:
                case SparqlQueryType.DescribeAll:
                    //Some kind of Graph
                    this._endpoint.QueryWithResultGraph(rdfHandler, sparqlQuery);
                    break;

                case SparqlQueryType.Unknown:
                default:
                    //Error
                    throw new RdfQueryException("Unknown Query Type was used, unable to determine how to process the response");
                }
            }
            else
            {
                //If we're skipping local parsing then we'll need to just make a raw query and process the response
                using (HttpWebResponse response = this._endpoint.QueryRaw(sparqlQuery))
                {
                    try
                    {
                        //Is the Content Type referring to a Sparql Result Set format?
                        ISparqlResultsReader sparqlParser = MimeTypesHelper.GetSparqlParser(response.ContentType);
                        sparqlParser.Load(resultsHandler, new StreamReader(response.GetResponseStream()));
                        response.Close();
                    }
                    catch (RdfParserSelectionException)
                    {
                        //If we get a Parser Selection exception then the Content Type isn't valid for a Sparql Result Set

                        //Is the Content Type referring to a RDF format?
                        IRdfReader rdfParser = MimeTypesHelper.GetParser(response.ContentType);
                        rdfParser.Load(rdfHandler, new StreamReader(response.GetResponseStream()));
                        response.Close();
                    }
                }
            }
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Makes a Query where the expected Result is an RDF Graph ie. CONSTRUCT and DESCRIBE Queries
 /// </summary>
 /// <param name="handler">RDF Handler</param>
 /// <param name="sparqlQuery">SPARQL Query String</param>
 public virtual void QueryWithResultGraph(IRdfHandler handler, String sparqlQuery)
 {
     try
     {
         //Make the Query
         using (HttpWebResponse httpResponse = this.QueryInternal(sparqlQuery, this.RdfAcceptHeader))
         {
             //Parse into a Graph based on Content Type
             String     ctype  = httpResponse.ContentType;
             IRdfReader parser = MimeTypesHelper.GetParser(ctype);
             parser.Load(handler, new StreamReader(httpResponse.GetResponseStream()));
             httpResponse.Close();
         }
     }
     catch (WebException webEx)
     {
         if (webEx.Response != null)
         {
             Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
         }
         //Some sort of HTTP Error occurred
         throw new RdfQueryException("A HTTP Error occurred when trying to make the SPARQL Query, see inner exception for details", webEx);
     }
     catch (RdfException)
     {
         //Some problem with the RDF or Parsing thereof
         throw;
     }
 }
        /// <summary>
        /// Gets the raw Similarity Graph for the Knowledge Base.
        /// </summary>
        /// <param name="number">Number of Similar Individuals.</param>
        /// <param name="individual">QName of a Individual to find Similar Individuals to.</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 SimilarityRaw(int number, String individual, GraphCallback callback, Object state)
        {
            if (number < 1)
            {
                throw new RdfReasoningException("Pellet Server requires the number of Similar Individuals to be at least 1");
            }

            String requestUri = _similarityUri + number + "/" + individual;

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

            request.Method = Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(MimeTypes.Where(t => !t.Equals("text/json")), MimeTypesHelper.SupportedRdfMimeTypes);

            Tools.HttpDebugRequest(request);

            try
            {
                request.BeginGetResponse(result =>
                {
                    try
                    {
                        using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                        {
                            Tools.HttpDebugResponse(response);
                            IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                            Graph g           = new Graph();
                            parser.Load(g, new StreamReader(response.GetResponseStream()));

                            response.Close();
                            callback(g, 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.º 11
0
        /// <summary>
        /// Gets the Raw Predictions Graph from the Knowledge Base
        /// </summary>
        /// <param name="individual">QName of an Individual</param>
        /// <param name="property">QName of a Property</param>
        /// <returns></returns>
        public IGraph PredictRaw(String individual, String property)
        {
            String requestUri = _predictUri + individual + "/" + property;

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

            request.Method = Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(MimeTypes.Where(t => !t.Equals("text/json")), MimeTypesHelper.SupportedRdfMimeTypes);

            Tools.HttpDebugRequest(request);

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Tools.HttpDebugResponse(response);

                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph      g      = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    return(g);
                }
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null)
                {
                    Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                }
                throw new RdfReasoningException("A HTTP error occurred while communicating with the Pellet Server", webEx);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Loads a Graph from the Protocol Server
        /// </summary>
        /// <param name="handler">RDF Handler</param>
        /// <param name="graphUri">URI of the Graph to load</param>
        public virtual void LoadGraph(IRdfHandler handler, String graphUri)
        {
            String retrievalUri = this._serviceUri;

            if (graphUri != null && !graphUri.Equals(String.Empty))
            {
                retrievalUri += "?graph=" + Uri.EscapeDataString(graphUri);
            }
            else
            {
                retrievalUri += "?default";
            }
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(retrievalUri);
                request.Method = "GET";
                request.Accept = MimeTypesHelper.HttpAcceptHeader;
                request        = base.GetProxiedRequest(request);

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

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    //Parse the retrieved RDF
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    parser.Load(handler, new StreamReader(response.GetResponseStream()));

                    //If we get here then it was OK
                    response.Close();
                }
            }
            catch (WebException webEx)
            {
                //If the error is a 404 then return false
                //Any other error caused the function to throw an error
                if (webEx.Response != null)
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                    }
#endif
                }
                throw new RdfStorageException("A HTTP Error occurred while trying to load a Graph from the Store", webEx);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Loads a Graph from the Store
        /// </summary>
        /// <param name="handler">RDF Handler</param>
        /// <param name="graphUri">URI of the Graph to load</param>
        /// <remarks>
        /// If an empty/null URI is specified then the Default Graph of the Store will be loaded
        /// </remarks>
        public void LoadGraph(IRdfHandler handler, String graphUri)
        {
            try
            {
                HttpWebRequest request;
                Dictionary <String, String> serviceParams = new Dictionary <string, string>();

                String tID        = (this._activeTrans == null) ? String.Empty : "/" + this._activeTrans;
                String requestUri = this._kb + tID + "/query";
                SparqlParameterizedString construct = new SparqlParameterizedString();
                if (!graphUri.Equals(String.Empty))
                {
                    construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH @graph { ?s ?p ?o } }";
                    construct.SetUri("graph", UriFactory.Create(graphUri));
                }
                else
                {
                    construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }";
                }
                serviceParams.Add("query", construct.ToString());

                request = this.CreateRequest(requestUri, MimeTypesHelper.HttpAcceptHeader, "GET", serviceParams);

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

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    parser.Load(handler, new StreamReader(response.GetResponseStream()));
                    response.Close();
                }
            }
            catch (WebException webEx)
            {
#if DEBUG
                if (Options.HttpDebugging)
                {
                    if (webEx.Response != null)
                    {
                        Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                    }
                }
#endif
                throw new RdfStorageException("A HTTP Error occurred while trying to load a Graph from the Store", webEx);
            }
        }
Ejemplo n.º 14
0
        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Uri u = new Uri(this.txtUri.Text);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(u.ToString());
                request.Accept = MimeTypesHelper.HttpAcceptHeader + ",*.*";
                String data;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    data = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    try
                    {
                        this._parser = MimeTypesHelper.GetParser(response.ContentType);
                        if (this._parser is NTriplesParser)
                        {
                            if (!response.ContentType.Equals("text/plain"))
                            {
                                this._parser = null;
                            }
                        }
                    }
                    catch (RdfParserSelectionException)
                    {
                        //Ignore here as we'll try and set the parser in another way next
                    }
                    response.Close();
                }

                this._data = data;
                if (this._parser == null)
                {
                    this._parser = StringParser.GetParser(data);
                    if (this._parser is NTriplesParser)
                    {
                        this._parser = null;
                    }
                }
                this._u = u;

                this.DialogResult = true;
                this.Close();
            }
            catch (UriFormatException)
            {
                MessageBox.Show("You have failed to enter a valid URI", "Invalid URI");
            }
            catch (WebException webEx)
            {
                MessageBox.Show("A HTTP error occurred opening the URI: " + webEx.Message, "Open URI Failed");
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while opening the URI: " + ex.Message, "Open URI Failed");
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Loads a Graph from the Store
        /// </summary>
        /// <param name="handler">RDF Handler</param>
        /// <param name="graphUri">Uri of the Graph to load</param>
        /// <remarks>If a Null/Empty Uri is specified then the default graph (statements with no context in Sesame parlance) will be loaded</remarks>
        public virtual void LoadGraph(IRdfHandler handler, String graphUri)
        {
            try
            {
                HttpWebRequest request;
                Dictionary <String, String> serviceParams = new Dictionary <string, string>();

                String requestUri = this._repositoriesPrefix + this._store + "/statements";
                if (!graphUri.Equals(String.Empty))
                {
                    //if (this._fullContextEncoding)
                    //{
                    serviceParams.Add("context", "<" + graphUri + ">");
                    //}
                    //else
                    //{
                    //    serviceParams.Add("context", graphUri);
                    //}
                }

                request = this.CreateRequest(requestUri, MimeTypesHelper.HttpAcceptHeader, "GET", serviceParams);

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

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    parser.Load(handler, new StreamReader(response.GetResponseStream()));
                    response.Close();
                }
            }
            catch (WebException webEx)
            {
#if DEBUG
                if (Options.HttpDebugging)
                {
                    if (webEx.Response != null)
                    {
                        Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                    }
                }
#endif
                throw new RdfStorageException("A HTTP Error occurred while trying to load a Graph from the Store", webEx);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Extracts the Graph which comprises the class hierarchy.
        /// </summary>
        /// <param name="callback">Callback for when the operation completes.</param>
        /// <param name="state">State to be passed 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 Classify(GraphCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Endpoint.Uri);

            request.Method = Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(MimeTypes, MimeTypesHelper.SupportedRdfMimeTypes);

            Tools.HttpDebugRequest(request);

            try
            {
                request.BeginGetResponse(result =>
                {
                    try
                    {
                        using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                        {
                            Tools.HttpDebugResponse(response);

                            IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                            Graph g           = new Graph();
                            parser.Load(g, new StreamReader(response.GetResponseStream()));

                            response.Close();
                            callback(g, 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.º 17
0
        /// <summary>
        /// Makes a Query asynchronously where the expected Result is an RDF Graph ie. CONSTRUCT and DESCRIBE Queries
        /// </summary>
        /// <param name="query">SPARQL Query String</param>
        /// <param name="callback">Callback to invoke when the query completes</param>
        /// <param name="state">State to pass to the callback</param>
        public void QueryWithResultGraph(String query, GraphCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Uri);

            request.Method      = "POST";
            request.ContentType = MimeTypesHelper.WWWFormURLEncoded;
            request.Accept      = MimeTypesHelper.HttpAcceptHeader;

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

            request.BeginGetRequestStream(result =>
            {
                Stream stream = request.EndGetRequestStream(result);
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.Write("query=");
                    writer.Write(HttpUtility.UrlEncode(query));

                    foreach (String u in this.DefaultGraphs)
                    {
                        writer.Write("&default-graph-uri=");
                        writer.Write(Uri.EscapeDataString(u));
                    }
                    foreach (String u in this.NamedGraphs)
                    {
                        writer.Write("&named-graph-uri=");
                        writer.Write(Uri.EscapeDataString(u));
                    }

                    writer.Close();
                }

                request.BeginGetResponse(innerResult =>
                {
                    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(innerResult);
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph g           = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    callback(g, state);
                }, null);
            }, null);
        }
Ejemplo n.º 18
0
        private string ParseBody(RdfFormat contentType)
        {
            var parser = MimeTypesHelper.GetParser(contentType.MediaTypes.First());

            var writer = new WriteToStringHandler(typeof(VDS.RDF.Writing.Formatting.NTriplesFormatter));

            using (var reader = new StreamReader(Request.Body))
            {
                parser.Load(writer, reader);
            }
            return(writer.ToString());
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Gets the raw Cluster Graph for the Knowledge Base
        /// </summary>
        /// <param name="number">Number of Clusters</param>
        /// <param name="type">QName of a Type to Cluster around</param>
        /// <returns></returns>
        public IGraph ClusterRaw(int number, String type)
        {
            if (number < 2)
            {
                throw new RdfReasoningException("Pellet Server requires the number of Clusters to be at least 2");
            }

            String requestUri = this._clusterUri + number + "/" + type;

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

            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(this.MimeTypes.Where(t => !t.Equals("text/json")), MimeTypesHelper.SupportedRdfMimeTypes);

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

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph      g      = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    return(g);
                }
            }
            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 the Pellet Server", webEx);
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Loads a Graph from the Joseki store
        /// </summary>
        /// <param name="handler">RDF Handler</param>
        /// <param name="graphUri">URI of the Graph to load</param>
        public void LoadGraph(IRdfHandler handler, String graphUri)
        {
            try
            {
                HttpWebRequest request;
                Dictionary <String, String> serviceParams = new Dictionary <string, string>();

                String query = "CONSTRUCT {?s ?p ?o}";
                if (!graphUri.Equals(String.Empty))
                {
                    query += " FROM <" + graphUri.ToString().Replace(">", "\\>") + ">";
                }
                query += " WHERE {?s ?p ?o}";
                serviceParams.Add("query", query);

                request = this.CreateRequest(this._queryService, MimeTypesHelper.HttpAcceptHeader, "GET", serviceParams);

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

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif

                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    parser.Load(handler, new StreamReader(response.GetResponseStream()));
                    response.Close();
                }
            }
            catch (WebException webEx)
            {
#if DEBUG
                if (Options.HttpDebugging)
                {
                    if (webEx.Response != null)
                    {
                        Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                    }
                }
#endif
                throw new RdfStorageException("A HTTP Error occurred while communicating with Joseki", webEx);
            }
        }
Ejemplo n.º 21
0
        private void DescribeInternal(IRdfHandler handler, String resourceUri, String servicePath)
        {
            //Single about param
            Dictionary <String, String> ps = new Dictionary <string, string>();

            ps.Add("about", resourceUri);

            HttpWebRequest  request  = null;
            HttpWebResponse response = null;

            try
            {
                //Get the Request Object
                request        = this.CreateRequest(servicePath, ps);
                request.Method = "GET";
                request.Accept = MimeTypesHelper.HttpAcceptHeader;

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

                using (response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif

                    //Get the relevant Parser
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    parser.Load(handler, new StreamReader(response.GetResponseStream()));
                    response.Close();
                }
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null)
                {
                    //Got a Response so we can analyse the Response Code
                    response = (HttpWebResponse)webEx.Response;
                    int code = (int)response.StatusCode;
                    throw Error(code, webEx);
                }
                //Didn't get a Response
                throw;
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Gets the Graph which can be parsed from the request body.
        /// </summary>
        /// <param name="context">HTTP Context.</param>
        /// <returns></returns>
        /// <remarks>
        /// In the event that there is no request body a null will be returned.
        /// </remarks>
        protected IGraph ParsePayload(IHttpContext context)
        {
            if (context.Request.ContentLength == 0)
            {
                return(null);
            }

            Graph      g      = new Graph();
            IRdfReader parser = MimeTypesHelper.GetParser(context.Request.ContentType);

            parser.Load(g, new StreamReader(context.Request.InputStream));
            g.NamespaceMap.Clear();

            return(g);
        }
Ejemplo n.º 23
0
 private void ParseResult(TextReader reader)
 {
     if (ResultFormat is RdfFormat)
     {
         ResultGraph = new Graph();
         var parser = MimeTypesHelper.GetParser(ResultFormat.MediaTypes);
         parser.Load(ResultGraph, reader);
     }
     else
     {
         ResultSet = new SparqlResultSet();
         var parser = MimeTypesHelper.GetSparqlParser(ResultFormat.MediaTypes[0]);
         parser.Load(ResultSet, reader);
     }
 }
Ejemplo n.º 24
0
 protected override void ImportUsingHandler(IRdfHandler handler)
 {
     this.Information = "Importing from File " + this._file;
     try
     {
         //Assume a RDF Graph
         IRdfReader reader = MimeTypesHelper.GetParser(MimeTypesHelper.GetMimeTypes(Path.GetExtension(this._file)));
         FileLoader.Load(handler, this._file, reader);
     }
     catch (RdfParserSelectionException)
     {
         //Assume a RDF Dataset
         FileLoader.LoadDataset(handler, this._file);
     }
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Loads a Graph from the Protocol Server
        /// </summary>
        /// <param name="handler">RDF Handler</param>
        /// <param name="graphUri">URI of the Graph to load</param>
        public virtual void LoadGraph(IRdfHandler handler, String graphUri)
        {
            String retrievalUri = this._serviceUri;

            if (graphUri != null && !graphUri.Equals(String.Empty))
            {
                retrievalUri += "?graph=" + Uri.EscapeDataString(graphUri);
            }
            else
            {
                retrievalUri += "?default";
            }
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(retrievalUri);
                request.Method = "GET";
                request.Accept = MimeTypesHelper.HttpAcceptHeader;
                request        = base.ApplyRequestOptions(request);

                Tools.HttpDebugRequest(request);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Tools.HttpDebugResponse(response);
                    // Parse the retrieved RDF
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    parser.Load(handler, new StreamReader(response.GetResponseStream()));

                    // If we get here then it was OK
                    response.Close();
                }
            }
            catch (WebException webEx)
            {
                // If the error is a 404 then return
                // Any other error caused the function to throw an error
                if (webEx.Response != null)
                {
                    Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                    if (((HttpWebResponse)webEx.Response).StatusCode == HttpStatusCode.NotFound)
                    {
                        return;
                    }
                }
                throw StorageHelper.HandleHttpError(webEx, "loading a Graph from");
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Extracts the Graph which comprises the class hierarchy
        /// </summary>
        public IGraph Classify()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Endpoint.Uri);

            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(this.MimeTypes, MimeTypesHelper.SupportedRdfMimeTypes);

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

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif

                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph      g      = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    return(g);
                }
            }
            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 the Pellet Server", webEx);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Loads the contents of the given File using a RDF Handler using the given RDF Parser
        /// </summary>
        /// <param name="handler">RDF Handler to use</param>
        /// <param name="filename">File to load from</param>
        /// <param name="parser">Parser to use</param>
        public static void Load(IRdfHandler handler, String filename, IRdfReader parser)
        {
            if (handler == null)
            {
                throw new RdfParseException("Cannot read RDF using a null RDF Handler");
            }
            if (filename == null)
            {
                throw new RdfParseException("Cannot read RDF from a null File");
            }

            //Try to get a Parser from the File Extension if one isn't explicitly specified
            if (parser == null)
            {
                try
                {
                    parser = MimeTypesHelper.GetParser(MimeTypesHelper.GetMimeTypes(Path.GetExtension(filename)));
                    RaiseWarning("Selected Parser " + parser.ToString() + " based on file extension, if this is incorrect consider specifying the parser explicitly");
                }
                catch (RdfParserSelectionException)
                {
                    //If error then we couldn't determine MIME Type from the File Extension
                    RaiseWarning("Unable to select a parser by determining MIME Type from the File Extension");
                }
            }

            if (parser == null)
            {
                //Unable to determine format from File Extension
                //Read file in locally and use the StringParser to select a parser
                RaiseWarning("Attempting to select parser based on analysis of the data file, this requires loading the file into memory");
                StreamReader reader = new StreamReader(filename);
                String       data   = reader.ReadToEnd();
                reader.Close();
                parser = StringParser.GetParser(data);
                RaiseWarning("Used the StringParser to guess the parser to use - it guessed " + parser.GetType().Name);
                parser.Warning += RaiseWarning;
                parser.Load(handler, new StringReader(data));
            }
            else
            {
                //Parser was selected based on File Extension or one was explicitly specified
                parser.Warning += RaiseWarning;
                parser.Load(handler, filename);
            }
        }
Ejemplo n.º 28
0
        public void ParsingRdfXmlNamespaceAttributes()
        {
            Graph          g       = new Graph();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dbpedia.org/resource/Southampton");

            request.Method = "GET";
            request.Accept = MimeTypesHelper.HttpAcceptHeader;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            IRdfReader      parser   = MimeTypesHelper.GetParser(response.ContentType);

            parser.Load(g, new StreamReader(response.GetResponseStream()));

            foreach (Triple t in g.Triples)
            {
                Console.WriteLine(t.ToString());
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Makes a Query asynchronously where the expected Result is an RDF Graph ie. CONSTRUCT and DESCRIBE Queries
        /// </summary>
        /// <param name="query">SPARQL Query String</param>
        /// <param name="handler">RDF Handler</param>
        /// <param name="callback">Callback to invoke when the query completes</param>
        /// <param name="state">State to pass to the callback</param>
        public void QueryWithResultGraph(IRdfHandler handler, String query, QueryCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Uri);

            request.Method      = "POST";
            request.ContentType = MimeTypesHelper.WWWFormURLEncoded;
            request.Accept      = this.ResultsAcceptHeader;

            Tools.HttpDebugRequest(request);

            request.BeginGetRequestStream(result =>
            {
                Stream stream = request.EndGetRequestStream(result);
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.Write("query=");
                    writer.Write(HttpUtility.UrlEncode(query));

                    foreach (String u in this.DefaultGraphs)
                    {
                        writer.Write("&default-graph-uri=");
                        writer.Write(HttpUtility.UrlEncode(u));
                    }
                    foreach (String u in this.NamedGraphs)
                    {
                        writer.Write("&named-graph-uri=");
                        writer.Write(HttpUtility.UrlEncode(u));
                    }

                    writer.Close();
                }

                request.BeginGetResponse(innerResult =>
                {
                    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(innerResult);
                    Tools.HttpDebugResponse(response);
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    parser.Load(handler, new StreamReader(response.GetResponseStream()));

                    callback(handler, null, state);
                }, null);
            }, null);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Processes a SPARQL Query against the Knowledge Base passing the results to the RDF or Results handler as appropriate
        /// </summary>
        /// <param name="rdfHandler">RDF Handler</param>
        /// <param name="resultsHandler">Results Handler</param>
        /// <param name="sparqlQuery">SPARQL Query</param>
        public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery)
        {
            SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(UriFactory.Create(this._sparqlUri));

            using (HttpWebResponse response = endpoint.QueryRaw(sparqlQuery))
            {
                try
                {
                    ISparqlResultsReader sparqlParser = MimeTypesHelper.GetSparqlParser(response.ContentType);
                    sparqlParser.Load(resultsHandler, new StreamReader(response.GetResponseStream()));
                }
                catch (RdfParserSelectionException)
                {
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    parser.Load(rdfHandler, new StreamReader(response.GetResponseStream()));
                }
                response.Close();
            }
        }