protected override void StartRdfInternal()
 {
     this._terms = new HashSet<INode>();
     this._termLabels = new Dictionary<INode, string>();
     this._termComments = new Dictionary<INode, string>();
     this._nsmap = new NamespaceMapper(true);
 }
Exemple #2
0
 /// <summary>
 /// Creates a new SPARQL Query
 /// </summary>
 protected internal SparqlQuery()
 {
     this._vars          = new Dictionary <string, SparqlVariable>();
     this._nsmapper      = new NamespaceMapper(true);
     this._defaultGraphs = new List <Uri>();
     this._namedGraphs   = new List <Uri>();
 }
Exemple #3
0
        /// <summary>
        /// Gets the Namespaces used in the Knowledge Base
        /// </summary>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to be passed to the callback</param>
        public void GetNamespaces(NamespaceCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Endpoint.Uri);

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

            Tools.HttpDebugRequest(request);

            String  jsonText;
            JObject json;

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

                    response.Close();
                }

                //Parse the Response into a NamespaceMapper
                NamespaceMapper nsmap = new NamespaceMapper(true);
                foreach (JProperty nsDef in json.Properties())
                {
                    nsmap.AddNamespace(nsDef.Name, UriFactory.Create((String)nsDef.Value));
                }

                callback(nsmap, state);
            }, null);
        }
Exemple #4
0
        private void StructuredToGraph(IEnumerable <Resource> input, Resource output)
        {
            ValidateMask(input, ResourceFormat.StructuredMask);

            if (Streaming)
            {
                var namespaceMapper = new NamespaceMapper();
                var formatter       = GetFormatter(output.Format, namespaceMapper);
                using (var writer = new StreamWriter(OpenOutput(output.TargetPath)))
                {
                    var handler = new NamespaceWriteThroughHandler(formatter, namespaceMapper, writer);
                    StructuredHandleInputs(input, handler);
                }
            }
            else
            {
                var rdfWriter = GetWriter(output.Format);
                if (rdfWriter is IPrettyPrintingWriter prettyWriter)
                {
                    prettyWriter.PrettyPrintMode = true;
                }
                var graph = new Graph();
                StructuredHandleInputs(input, new GraphHandler(graph));
                using (var writer = new StreamWriter(OpenOutput(output.TargetPath)))
                {
                    rdfWriter.Save(graph, writer);
                }
            }
        }
Exemple #5
0
 /// <summary>
 /// Starts RDF handling
 /// </summary>
 protected override void StartRdfInternal()
 {
     this._terms        = new HashSet <INode>();
     this._termLabels   = new Dictionary <INode, string>();
     this._termComments = new Dictionary <INode, string>();
     this._nsmap        = new NamespaceMapper(true);
 }
 /// <summary>
 /// Creates a new SPARQL Query
 /// </summary>
 internal SparqlQuery()
 {
     _vars          = new List <SparqlVariable>();
     _nsmapper      = new NamespaceMapper(true);
     _defaultGraphs = new List <Uri>();
     _namedGraphs   = new List <Uri>();
 }
 public void printURIResource(IResource resource)
 {
     if (getUsePrefixes())
     {
         String qname = qnameFor(resource);
         if (qname != null)
         {
             print(qname);
             return;
         }
         else if (getUseExtraPrefixes())
         {
             INamespaceMapper extras = new NamespaceMapper(); //ExtraPrefixes.getExtraPrefixes();
             foreach (String prefix in extras.Prefixes)
             {
                 String ns = extras.GetNamespaceUri(prefix).ToString();
                 if (resource.Uri.ToString().StartsWith(ns))
                 {
                     print(prefix);
                     print(":");
                     print(resource.Uri.ToString().Substring(ns.Length));
                     return;
                 }
             }
         }
     }
     print("<");
     print(resource.Uri.ToString());
     print(">");
 }
Exemple #8
0
 public virtual void Visit(NamespaceMapper mapper)
 {
     foreach (TypeMapper type in mapper.GetTypes())
     {
         Visit(type);
     }
 }
Exemple #9
0
        /// <summary>
        /// Gets the Namespaces used in the Knowledge Base
        /// </summary>
        /// <returns></returns>
        public NamespaceMapper GetNamespaces()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Endpoint.Uri);

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

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

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

                    response.Close();
                }

                //Parse the Response into a NamespaceMapper
                NamespaceMapper nsmap = new NamespaceMapper(true);
                foreach (JProperty nsDef in json.Properties())
                {
                    nsmap.AddNamespace(nsDef.Name, UriFactory.Create((String)nsDef.Value));
                }

                return(nsmap);
            }
            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);
            }
            catch (Exception ex)
            {
                throw new RdfReasoningException("Error occurred while parsing Namespace Service results", ex);
            }
        }
Exemple #10
0
 public DataAccess()
 {
     _configurationFilesDictionary =
         new Dictionary <string, Endpoint>(
             LoadConfigurationFiles(@"Data/JsonFiles/EndpointConfiguration"));
     _namespaceMapper = new NamespaceMapper();
     _namespaceMapper = LoadNamespacesFile(@"Data/JsonFiles/Namespaces/namespaces.json");
 }
Exemple #11
0
 private void SetupNamespaceMap()
 {
     _nsMap = new NamespaceMapper();
     _nsMap.AddNamespace("a", new Uri("http://tempuri.com/blah/"));
     _nsMap.AddNamespace("owl", new Uri("http://www.w3.org/2002/07/owl#"));
     _nsMap.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
     _nsMap.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#"));
 }
        public void WhenMapToDictionary_ShouldReturnDictionary()
        {
            INamespaceMapper nsMap = new NamespaceMapper();

            nsMap.AddNamespace("ex", new Uri("http://www.example.org/ns#"));

            IDictionary <string, string> result = NamespaceHelper.ToStringDictionary(nsMap);

            Assert.That(result, Is.Not.Null);
        }
        public INamespaceMapper CreateNamespaceMapper()
        {
            var result = new NamespaceMapper();

            result.Import(generalUris.CreateNamespaceMapper());
            result.AddNamespace("se", BaseUri);
            result.AddNamespace("tag", tagPrefix);
            result.AddNamespace("badge", badgePrefix);
            return(result);
        }
        public static INamespaceMapper ToIGraphNamespaceMap(IDictionary <string, string> namespaceMap)
        {
            INamespaceMapper rdfNamespaceMap = new NamespaceMapper();

            foreach (KeyValuePair <string, string> nsPair in namespaceMap)
            {
                rdfNamespaceMap.AddNamespace(nsPair.Key, new Uri(nsPair.Value));
            }
            return(rdfNamespaceMap);
        }
Exemple #15
0
        public static void Main(string[] args)
        {
            // Create a Console Logger:
            log = LoggerFactory
                  .Create(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Debug))
                  .CreateLogger <Program>();

            // We don't want to use a Graph to prevent Memory
            // from exploding while writing the Data:
            nodeFactory = new NodeFactory();

            // We don't want to write the full URL for every
            // triple, because that will lead to a large TTL
            // file with redundant data:
            namespaceMapper = new NamespaceMapper();

            namespaceMapper.AddNamespace("ge", Constants.NsAviationGeneral);
            namespaceMapper.AddNamespace("ap", Constants.NsAviationAirport);
            namespaceMapper.AddNamespace("ac", Constants.NsAviationtAircraft);
            namespaceMapper.AddNamespace("ca", Constants.NsAviationCarrier);
            namespaceMapper.AddNamespace("fl", Constants.NsAviationFlight);
            namespaceMapper.AddNamespace("we", Constants.NsAviationWeather);
            namespaceMapper.AddNamespace("st", Constants.NsAviationWeatherStation);

            // There is a memory-leak when using the default QNameOutputMapper,
            // which adds all URIs encountered to a cache for speedup. This leads
            // to problems with millions of unique URIs, so we define a
            // a QNameOutputMapper with the Cache removed:
            var outputMapper = new NonCachingQNameOutputMapper(namespaceMapper);

            // Create the TurtleFormatter with the Namespace Mappings:
            turtleFormatter = new TurtleFormatter(outputMapper);

            // Load the Base Data:
            log.LogDebug("Loading Base Data ...");

            var aircrafts = GetAircraftData(csvAircraftsFile).ToList();
            var carriers  = GetCarrierData(csvCarriersFile).ToList();
            var airports  = GetAirportData(csvAirportFile).ToList();
            var stations  = GetWeatherStationData(csvWeatherStationsFileName).ToList();

            using (FileStream fileStream = File.Create(@"G:\aviation_2014.ttl"))
            {
                using (StreamWriter writer = new StreamWriter(fileStream))
                {
                    WriteNamespaces(writer);
                    WriteAircrafts(writer, aircrafts);
                    WriteAirports(writer, airports);
                    WriteCarriers(writer, carriers);
                    WriteFlights(writer, aircrafts, airports, carriers);
                    WriteWeatherStations(writer, stations, airports);
                    WriteWeatherDatas(writer, stations);
                }
            }
        }
Exemple #16
0
        public INamespaceMapper CreateNamespaceMapper()
        {
            var result = new NamespaceMapper();

            result.AddNamespace("dc", new Uri("http://purl.org/dc/elements/1.1/"));
            result.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/"));

            result.AddNamespace("se", GlobalPrefix);
            result.AddNamespace(siteShortPrefix, SitePrefix);
            result.AddNamespace("se-owl", OntologyPrefix);
            result.AddNamespace("cr", CloseReasonPrefix);
            return(result);
        }
Exemple #17
0
        public QueryService()
        {
            _graph  = new Graph();
            _parser = new SparqlQueryParser();
            var ds = new InMemoryDataset(_graph);

            _processor = new LeviathanQueryProcessor(ds);

            _prefixes = new NamespaceMapper(true);
            _prefixes.AddNamespace("rua", UriFactory.Create("https://rabota.ua/"));
            _prefixes.AddNamespace("rdf", UriFactory.Create("http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
            _prefixes.AddNamespace("rdfs", UriFactory.Create("http://www.w3.org/2000/01/rdf-schema#"));
        }
        private static INamespaceMapper MergeNamespaceMaps(INamespaceMapper main, INamespaceMapper secondary)
        {
            NamespaceMapper nsmap = new NamespaceMapper(true);

            if (main != null)
            {
                nsmap.Import(main);
            }
            if (secondary != null)
            {
                nsmap.Import(secondary);
            }
            return(nsmap);
        }
Exemple #19
0
    public async Task ExecuteAotSparqlAction(AotSparqlOptions options)
    {
        if (options == null)
        {
            throw new ArgumentNullException(nameof(options));
        }
        using (var namespaceMap = new NamespaceMapper())
        {
            foreach (var entry in options.NamespaceMapping)
            {
                namespaceMap.AddNamespace(entry.Key, new Uri(entry.Value));
            }
            using (var moduleFactory = await OptionUtility.CreateExportModuleFactoryAsync(options.ExportModulePrefix, mwSiteProvider, logger))
                using (var executor = new AotSparqlExecutor(options.DataSource, namespaceMap, uri =>
                {
                    // Blank node.
                    if (uri == null)
                    {
                        return("_:");
                    }
                    // One.
                    if (uri == Utility.WikibaseRdfUnityEntity)
                    {
                        return("1");
                    }
                    if (namespaceMap.ReduceToQName(uri.ToString(), out var qname))
                    {
                        // Remove prefix for local entities.
                        if (qname.StartsWith("wd:", StringComparison.OrdinalIgnoreCase))
                        {
                            return(qname.Substring(3));
                        }
                        return(qname);
                    }
                    throw new InvalidOperationException($"Cannot reduce {uri} into its QName.");
                }, logger.ForContext <AotSparqlExecutor>()))
                {
                    var exporter = new AotSparqlModuleExporter(logger, moduleFactory, executor);
                    {
                        var(configSite, configModule) = await OptionUtility.ResolveSiteAndTitleAsync(options.ConfigModule, mwSiteProvider);

                        await exporter.LoadConfigFromModuleAsync(configSite, configModule);

                        logger.Information("Loaded config from {Module}.", options.ConfigModule);
                    }
                    await exporter.ExportModulesAsync();
                }
        }
    }
        private static void WriteOntology(GeneralUris generalUris, string destDir, VDS.RDF.INamespaceMapper nsMapper)
        {
            ConsoleHelper.WriteMilestone("Writing ontology ...");

            using (var tempNsMapper = new NamespaceMapper(false)) {
                tempNsMapper.Import(nsMapper);
                tempNsMapper.AddNamespace("owl", new Uri(NamespaceMapper.OWL));

                using (var destWriter = new SequentialTurtleWriter(File.CreateText(Path.Combine(destDir, "_ontology.ttl")), tempNsMapper)) {
                    WriteOntologyDefinitions(generalUris, destWriter);

                    GlobalData.UpdateStats(destWriter);
                }
            }
            Console.WriteLine(" done.");
        }
Exemple #21
0
        /// <summary>
        /// Gets the Namespaces used in the Knowledge Base
        /// </summary>
        /// <param name="callback">Callback to invoke 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 GetNamespaces(NamespaceCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Endpoint.Uri);

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

            Tools.HttpDebugRequest(request);

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

                            response.Close();
                        }

                        //Parse the Response into a NamespaceMapper
                        NamespaceMapper nsmap = new NamespaceMapper(true);
                        foreach (JProperty nsDef in json.Properties())
                        {
                            nsmap.AddNamespace(nsDef.Name, UriFactory.Create((String)nsDef.Value));
                        }

                        callback(nsmap, 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));
            }
        }
 /// <summary>
 /// Creates a new RDFa Evaluation Context
 /// </summary>
 /// <param name="baseUri">Base URI</param>
 /// <param name="nsmap">Namepace Map</param>
 public RdfAEvaluationContext(Uri baseUri, NamespaceMapper nsmap)
     : this(baseUri)
 {
     this._nsmapper = nsmap;
 }
Exemple #23
0
 /// <summary>
 /// Creates a new RDFa Evaluation Context
 /// </summary>
 /// <param name="baseUri">Base URI</param>
 /// <param name="nsmap">Namepace Map</param>
 public RdfAEvaluationContext(Uri baseUri, NamespaceMapper nsmap)
     : this(baseUri)
 {
     _nsmapper = nsmap;
 }
        protected override String RunTaskInternal()
        {
            // Start from an initial Original Query issued by user
            SparqlQuery initialQuery;

            try
            {
                initialQuery = this._parser.ParseFromString(this.OriginalQueryString);
            }
            catch (RdfParseException parseEx)
            {
                throw new RdfQueryException("Unable to parse the given SPARQL Query", parseEx);
            }

            if (initialQuery.QueryType != SparqlQueryType.Select && initialQuery.QueryType != SparqlQueryType.SelectDistinct)
            {
                throw new RdfQueryException("Only Sparql select Query with variables is supported for table format");
            }

            INamespaceMapper originalPrefixes = new NamespaceMapper(true);

            originalPrefixes.Import(initialQuery.NamespaceMap);
            initialQuery.NamespaceMap.Clear();

            // Get the predicates for first variable (entity subjects)
            // SELECT DISTINCT ?p (COUNT(?p) as ?count)
            // WHERE
            // {
            //   {
            //     # Original Query
            //   }
            //   ?sx ?p ?o.
            // }
            // GROUP BY ?p
            // Create a dynamic originalQuery

            SparqlVariable subject = initialQuery.Variables.FirstOrDefault(v => v.IsResultVariable);

            if (subject == null)
            {
                throw new RdfQueryException("At least one result variable is required to generate an entities query");
            }
            INode subjectNode = this._nodeFactory.CreateVariableNode(subject.Name);

            SparqlParameterizedString getPredicatesQuery = new SparqlParameterizedString();

            getPredicatesQuery.Namespaces  = originalPrefixes;
            getPredicatesQuery.CommandText = @"
SELECT DISTINCT ?p (COUNT(?p) as ?count)
WHERE
{";
            getPredicatesQuery.AppendSubQuery(initialQuery);
            getPredicatesQuery.CommandText += @"
  @subject ?p ?o.
}
GROUP BY ?p";
            getPredicatesQuery.SetParameter("subject", subjectNode);

            try
            {
                // Get predicates and number of usages
                this.Information = "Running query to extract predicates for entities selected by original query...";
                SparqlResultSet sparqlResults = (SparqlResultSet)this._storage.Query(getPredicatesQuery.ToString());
                if (sparqlResults == null)
                {
                    throw new RdfQueryException("Unexpected results type received while trying to build entities query");
                }

                List <String> selectColumns = new List <String>();
                selectColumns.Add(subject.Name);
                SparqlParameterizedString entitiesQuery = new SparqlParameterizedString();
                entitiesQuery.Namespaces.Import(getPredicatesQuery.Namespaces);
                entitiesQuery.SetParameter("subject", subjectNode);

                // For each predicate add a column and an appropriate OPTIONAL clause
                int           predicateIndex  = 0;
                StringBuilder optionalFilters = new StringBuilder();
                this.Information = "Generating Entities Query...";
                foreach (SparqlResult sparqlResult in sparqlResults)
                {
                    if (!sparqlResult.HasBoundValue("p"))
                    {
                        continue;
                    }
                    INode       predicate      = sparqlResult["p"];
                    IValuedNode count          = sparqlResult["count"].AsValuedNode();
                    long        predicateCount = count != null?count.AsInteger() : 0;

                    // For each predicate with predicateCount > _minValuesPerPredicateLimit add a new column and an optional filter in where clause
                    if (predicateCount <= _minValuesPerPredicateLimit)
                    {
                        continue;
                    }
                    predicateIndex++;
                    String predicateColumnName = GetColumnName(predicate, entitiesQuery.Namespaces);
                    if (predicateColumnName == null)
                    {
                        continue;
                    }
                    selectColumns.Add(predicateColumnName);

                    optionalFilters.AppendLine("  OPTIONAL { @subject @predicate" + predicateIndex + " ?" + predicateColumnName + " }");
                    entitiesQuery.SetParameter("predicate" + predicateIndex, predicate);
                }

                if (selectColumns.Count == 1)
                {
                    throw new RdfQueryException("No predicates which matched the criteria were found so an entities query cannot be generated");
                }

                entitiesQuery.CommandText = "SELECT DISTINCT ";
                foreach (String column in selectColumns)
                {
                    entitiesQuery.CommandText += "?" + column + " ";
                }
                entitiesQuery.CommandText += @"
WHERE
{
";
                entitiesQuery.AppendSubQuery(initialQuery);
                entitiesQuery.CommandText += optionalFilters.ToString();
                entitiesQuery.CommandText += @"
}";

                this.Information      = "Generated Entities Query with " + (selectColumns.Count - 1) + " Predicate Columns";
                this.OutputTableQuery = entitiesQuery.ToString();
            }
            catch (Exception)
            {
                this.OutputTableQuery = null;
                throw;
            }

            return(this.OutputTableQuery);
        }
Exemple #25
0
        /// <summary>
        /// Gets the Namespaces used in the Knowledge Base
        /// </summary>
        /// <returns></returns>
        public NamespaceMapper GetNamespaces()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Endpoint.Uri);
            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = "text/json";

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

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

                    response.Close();
                }

                //Parse the Response into a NamespaceMapper
                NamespaceMapper nsmap = new NamespaceMapper(true);
                foreach (JProperty nsDef in json.Properties())
                {
                    nsmap.AddNamespace(nsDef.Name, UriFactory.Create((String)nsDef.Value));
                }

                return nsmap;
            }
            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);
            }
            catch (Exception ex)
            {
                throw new RdfReasoningException("Error occurred while parsing Namespace Service results", ex);
            }
        }
Exemple #26
0
        /// <summary>
        /// Gets the Namespaces used in the Knowledge Base
        /// </summary>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to be passed to the callback</param>
        public void GetNamespaces(NamespaceCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Endpoint.Uri);
            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = "text/json";

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

            String jsonText;
            JObject json;
            request.BeginGetResponse(result =>
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                    {
            #if DEBUG
                        if (Options.HttpDebugging)
                        {
                            Tools.HttpDebugResponse(response);
                        }
            #endif
                        jsonText = new StreamReader(response.GetResponseStream()).ReadToEnd();
                        json = JObject.Parse(jsonText);

                        response.Close();
                    }

                    //Parse the Response into a NamespaceMapper
                    NamespaceMapper nsmap = new NamespaceMapper(true);
                    foreach (JProperty nsDef in json.Properties())
                    {
                        nsmap.AddNamespace(nsDef.Name, UriFactory.Create((String)nsDef.Value));
                    }

                    callback(nsmap, state);
                }, null);
        }
Exemple #27
0
        private void Parse(TriGParserContext context)
        {
            try
            {
                context.Handler.StartRdf();

                //Expect a BOF Token
                IToken first = context.Tokens.Dequeue();
                if (first.TokenType != Token.BOF)
                {
                    throw ParserHelper.Error("Unexpected Token '" + first.GetType().ToString() + "' encountered, expected a BOF Token", first);
                }

                //Expect either a Directive or a Graph
                IToken next;
                do
                {
                    next = context.Tokens.Peek();
                    switch (next.TokenType)
                    {
                    case Token.COMMENT:
                        //Discard
                        context.Tokens.Dequeue();
                        break;

                    case Token.EOF:
                        //End of File
                        context.Tokens.Dequeue();
                        break;

                    case Token.BASEDIRECTIVE:
                    case Token.PREFIXDIRECTIVE:
                        //Parse a Directive
                        this.TryParseDirective(context);
                        break;

                    case Token.QNAME:
                    case Token.URI:
                    case Token.LEFTCURLYBRACKET:
                        //Parse a Graph

                        if (context.Syntax != TriGSyntax.Original)
                        {
                            //We must take care here because @prefix and @base directives may be Graph scoped so anything visible currently
                            //remains visible and must be restored afterwards but anything inside the Graph is not visible outside of it
                            Uri extBase            = context.BaseUri;
                            INamespaceMapper nsmap = new NamespaceMapper(context.Namespaces);

                            this.TryParseGraph(context);

                            //After we parse the Graph restore the state
                            if (!context.Handler.HandleBaseUri(extBase))
                            {
                                ParserHelper.Stop();
                            }
                            context.BaseUri = extBase;
                            context.Namespaces.Clear();
                            foreach (String prefix in nsmap.Prefixes)
                            {
                                if (!context.Handler.HandleNamespace(prefix, nsmap.GetNamespaceUri(prefix)))
                                {
                                    ParserHelper.Stop();
                                }
                            }
                            context.Namespaces.Import(nsmap);
                        }
                        else
                        {
                            //With the old syntax declarations are file scoped so no need to worry about graph scoping
                            this.TryParseGraph(context);
                        }
                        break;

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

                context.Handler.EndRdf(true);
            }
            catch (RdfParsingTerminatedException)
            {
                context.Handler.EndRdf(true);
                //Discard this - it justs means the Handler told us to stop
            }
            catch
            {
                context.Handler.EndRdf(false);
                throw;
            }
        }
Exemple #28
0
 /// <summary>
 /// Creates a new SPARQL Query
 /// </summary>
 protected internal SparqlQuery()
 {
     this._vars = new Dictionary<string, SparqlVariable>();
     this._nsmapper = new NamespaceMapper(true);
     this._defaultGraphs = new List<Uri>();
     this._namedGraphs = new List<Uri>();
 }
        public void NamespaceMapperEvent()
        {
            bool eventRaised = false;

            NamespaceChanged added = delegate(String prefix, Uri u) { eventRaised = true; };
            NamespaceChanged changed = delegate(String prefix, Uri u) { eventRaised = true; };
            NamespaceChanged removed = delegate(String prefix, Uri u) { eventRaised = true; };

            NamespaceMapper nsmap = new NamespaceMapper();
            nsmap.NamespaceAdded += added;
            nsmap.NamespaceModified += changed;
            nsmap.NamespaceRemoved += removed;

            Console.WriteLine("Trying to add the RDF Namespace, this should already be defined");
            nsmap.AddNamespace("rdf", new Uri(NamespaceMapper.RDF));
            Assert.AreEqual(false, eventRaised, "Trying to add a Namespace that already exists should have no effect");
            eventRaised = false;
            Console.WriteLine();

            Console.WriteLine("Trying to add an example Namespace which isn't defined");
            nsmap.AddNamespace("ex", new Uri("http://example.org/"));
            Assert.AreEqual(true, eventRaised, "Adding a new Namespace should raise the NamespaceAdded event");
            eventRaised = false;
            Console.WriteLine(nsmap.GetNamespaceUri("ex").ToString());
            Console.WriteLine();

            Console.WriteLine("Trying to modify the example Namespace");
            nsmap.AddNamespace("ex", new Uri("http://example.org/test/"));
            Assert.AreEqual(true, eventRaised, "Modifying a Namespace should raise the NamespaceModified event");
            eventRaised = false;
            Console.WriteLine(nsmap.GetNamespaceUri("ex").ToString());
            Console.WriteLine();

            Console.WriteLine("Trying to remove the example Namespace");
            nsmap.RemoveNamespace("ex");
            Assert.AreEqual(true, eventRaised, "Removing an existing Namespace should raise the NamespaceRemoved event");
            eventRaised = false;
            Console.WriteLine();

            Console.WriteLine("Trying to remove a non-existent Namespace");
            nsmap.RemoveNamespace("ex");
            Assert.AreEqual(false, eventRaised, "Removing a non-existent Namespace should not raise the NamespaceRemoved event");
            eventRaised = false;
            Console.WriteLine();

            Console.WriteLine("Adding some example Namespace back in again for an import test");
            nsmap.AddNamespace("ex", new Uri("http://example.org/"));
            nsmap.AddNamespace("ns0", new Uri("http://example.org/clashes/"));

            Console.WriteLine("Creating another Namespace Mapper with the ex prefix mapped to a different URI");
            NamespaceMapper nsmap2 = new NamespaceMapper();
            nsmap2.AddNamespace("ex", new Uri("http://example.org/test/"));

            Console.WriteLine("Importing the new NamespaceMapper into the original");
            nsmap.Import(nsmap2);
            Console.WriteLine("NamespaceMapper now contains the following Namespaces:");
            foreach (String prefix in nsmap.Prefixes)
            {
                Console.WriteLine("\t" + prefix + " <" + nsmap.GetNamespaceUri(prefix).ToString() + ">");
            }
            Assert.AreEqual(nsmap.GetNamespaceUri("ex"), new Uri("http://example.org/"), "ex prefix should be mapped to the original URI");
            Assert.AreEqual(nsmap.GetNamespaceUri("ns1"), new Uri("http://example.org/test/"), "ex prefix from other NamespaceMapper should get remapped to ns1 since ns0 is already in use");
        }