Example #1
0
    public static void Main()
    {
        Store store = new MemoryStore();

        store.Import(RdfReader.LoadFromUri(new Uri(example_foaf_file)));

        // Dump out the data, for fun
        using (RdfWriter writer = new RdfXmlWriter(Console.Out)) {
            writer.Write(store);
        }

        Console.WriteLine("These are the people in the file:");
        foreach (Statement s in store.Select(new Statement(null, rdftype, foafPerson)))
        {
            foreach (Resource r in store.SelectObjects(s.Subject, foafname))
            {
                Console.WriteLine(r);
            }
        }
        Console.WriteLine();

        Console.WriteLine("And here's RDF/XML just for some of the file:");
        using (RdfWriter w = new RdfXmlWriter(Console.Out)) {
            store.Select(new Statement(null, foafname, null), w);
            store.Select(new Statement(null, foafknows, null), w);
        }
        Console.WriteLine();
    }
Example #2
0
        private async void OnRebuildDatabase(object sender, RoutedEventArgs e)
        {
            var path = Windows.Storage.ApplicationData.Current.LocalFolder.Path;

            System.Diagnostics.Debug.WriteLine($"INFO: local files are in {path}");
            var bookdb = BookDataContext.Get();
            int nbook  = await RdfReader.ReadDirAsync(bookdb);

            if (nbook < 5)
            {
                App.Error($"Error when rebuilding database; only got {nbook} for {path}");
            }
            // Will clear out the old db and save as needed.
        }
Example #3
0
    public static void Main()
    {
        // Create the instance data

        MemoryStore dataModel = new MemoryStore();

        BNode me  = new BNode("me");
        BNode you = new BNode("you");

        Entity rdfType    = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
        Entity rdfsLabel  = "http://www.w3.org/2000/01/rdf-schema#label";
        Entity foafPerson = "http://xmlns.com/foaf/0.1/Person";
        Entity foafAgent  = "http://xmlns.com/foaf/0.1/Agent";
        Entity foafName   = "http://xmlns.com/foaf/0.1/name";

        dataModel.Add(new Statement(me, rdfType, foafPerson));
        dataModel.Add(new Statement(you, rdfType, foafPerson));
        dataModel.Add(new Statement(me, foafName, (Literal)"John Doe"));
        dataModel.Add(new Statement(you, foafName, (Literal)"Sam Smith"));

        // Create the RDFS engine and apply it to the data model.

        RDFS engine = new RDFS();

        engine.LoadSchema(RdfReader.LoadFromUri(new Uri("http://xmlns.com/foaf/0.1/index.rdf")));

        dataModel.AddReasoner(engine);

        // Query the data model

        // Ask for who are typed as Agents.  Note that the people are
        // typed as foaf:Person, and the schema asserts that foaf:Person
        // is a subclass of foaf:Agent.
        Console.WriteLine("Who are Agents?");
        foreach (Entity r in dataModel.SelectSubjects(rdfType, foafAgent))
        {
            Console.WriteLine("\t" + r);
        }

        // Ask for the rdfs:labels of everyone.  Note that the data model
        // has foaf:names for the people, and the schema asserts that
        // foaf:name is a subproperty of rdfs:label.
        Console.WriteLine("People's labels:");
        foreach (Statement s in dataModel.Select(new Statement(null, rdfsLabel, null)))
        {
            Console.WriteLine("\t" + s);
        }
    }
Example #4
0
    public static void Main(string[] args)
    {
        string uri = "http://www.mozilla.org/news.rdf";

        if (args.Length > 0)
        {
            uri = args[0];
        }

        MemoryStore store = new MemoryStore();

        // Here's one way...

        store.Import(RdfReader.LoadFromUri(new Uri(uri)));

        using (RdfWriter writer = new N3Writer(Console.Out))
            store.Select(writer);

        // Or....

        RdfReader file = RdfReader.LoadFromUri(new Uri(uri));

        file.Select(new StatementPrinter());
    }
Example #5
0
        public override void Select(StatementSink storage)
        {
            foreach (string infile in files)
            {
                if (!quiet)
                {
                    Console.Error.Write(infile + " ");
                }

                try {
                    DateTime start = DateTime.Now;

                    StatementFilterSink filter = new StatementFilterSink(storage);

                    if (format == null || format != "spec")
                    {
                        string fmt = format;
                        if (fmt == null)
                        {
                            // Use file extension to override default parser type.
                            if (infile.StartsWith("http:"))
                            {
                                fmt = "url";
                            }
                            else if (infile.EndsWith(".nt") || infile.EndsWith(".n3") || infile.EndsWith(".ttl"))
                            {
                                fmt = "n3";
                            }
                            else if (infile.EndsWith(".xml") || infile.EndsWith(".rdf"))
                            {
                                fmt = "xml";
                            }
                            else
                            {
                                Console.Error.WriteLine("Unrecognized file extension in " + infile + ": Trying RDF/XML.");
                                fmt = "xml";
                            }
                        }

                        using (RdfReader parser = RdfReader.Create(fmt, infile)) {
                            if (baseuri != null)
                            {
                                parser.BaseUri = baseuri;
                            }
                            if (meta != null)
                            {
                                parser.Meta = meta;
                            }

                            if (storage is RdfWriter)
                            {
                                ((RdfWriter)storage).Namespaces.AddFrom(parser.Namespaces);
                            }

                            try {
                                parser.Select(filter);
                            } finally {
                                if (parser.Warnings.Count > 0)
                                {
                                    Console.Error.WriteLine("\nThere were warnings parsing this file:");
                                }
                                foreach (string warning in parser.Warnings)
                                {
                                    Console.Error.WriteLine("> " + warning);
                                }
                            }
                        }
                    }
                    else
                    {
                        StatementSource src = Store.Create(infile);
                        src.Select(filter);
                        if (src is IDisposable)
                        {
                            ((IDisposable)src).Dispose();
                        }
                    }

                    totalStatementsRead += filter.StatementCount;

                    TimeSpan time = DateTime.Now - start;

                    if (!quiet)
                    {
                        Console.Error.WriteLine(" {0}m{1}s, {2} statements, {3} st/sec", (int)time.TotalMinutes, (int)time.Seconds, filter.StatementCount, time.TotalSeconds == 0 ? "?" : ((int)(filter.StatementCount / time.TotalSeconds)).ToString());
                    }
                } catch (ParserException e) {
                    Console.Error.WriteLine(" " + e.Message);
                } catch (Exception e) {
                    Console.Error.WriteLine("\n" + e + "\n");
                }
            }
        }
Example #6
0
    public static void Main(string[] args)
    {
        System.Net.ServicePointManager.Expect100Continue = false;

        Opts opts = new Opts();

        opts.ProcessArgs(args);

        if (opts.RemainingArguments.Length != 1)
        {
            opts.DoHelp();
            return;
        }

        string baseuri = "query://query/#";

        QueryResultSink qs;

        if (opts.format == "simple")
        {
            qs = new PrintQuerySink();
        }
        else if (opts.format == "html")
        {
            qs = new HTMLQuerySink(Console.Out);
        }
        else if (opts.format == "xml")
        {
            qs = new SparqlXmlQuerySink(Console.Out);
        }
        else if (opts.format == "lubm")
        {
            qs = new LUBMReferenceAnswerOutputQuerySink();
        }
        else if (opts.format == "csv")
        {
            qs = new CSVQuerySink();
        }
        else
        {
            Console.Error.WriteLine("Invalid output format.");
            return;
        }

        Query query;

        MemoryStore queryModel = null;

                #if !DOTNET2
        System.Collections.ICollection queryModelVars = null;
                #else
        System.Collections.Generic.ICollection <Variable> queryModelVars = null;
                #endif

        Store model = Store.Create(opts.RemainingArguments[0]);

        if (opts.type == "rsquary")
        {
            RdfReader queryparser = RdfReader.Create("n3", "-");
            queryparser.BaseUri = baseuri;
            queryModel          = new MemoryStore(queryparser);
            queryModelVars      = queryparser.Variables;
            query = new GraphMatch(queryModel);
        }
        else if (opts.type == "sparql" && model.DataSources.Count == 1 && model.DataSources[0] is SemWeb.Remote.SparqlSource)
        {
            string querystring = Console.In.ReadToEnd();
            ((SemWeb.Remote.SparqlSource)model.DataSources[0]).RunSparqlQuery(querystring, Console.Out);
            return;
        }
        else if (opts.type == "sparql")
        {
            string querystring = Console.In.ReadToEnd();
            query = new SparqlEngine(querystring);
        }
        else
        {
            throw new Exception("Invalid query format: " + opts.type);
        }

        if (opts.limit > 0)
        {
            query.ReturnLimit = opts.limit;
        }

        //Console.Error.WriteLine(query.GetExplanation());

        if (query is SparqlEngine && ((SparqlEngine)query).Type != SparqlEngine.QueryType.Select)
        {
            SparqlEngine sparql = (SparqlEngine)query;
            sparql.Run(model, Console.Out);
        }
        else if (model is QueryableSource && queryModel != null)
        {
            SemWeb.Query.QueryOptions qopts = new SemWeb.Query.QueryOptions();
            qopts.DistinguishedVariables = queryModelVars;

            // Replace bnodes in the query with Variables
            int bnodectr = 0;
            foreach (Entity e in queryModel.GetEntities())
            {
                if (e is BNode && !(e is Variable))
                {
                    BNode b = (BNode)e;
                    queryModel.Replace(e, new Variable(b.LocalName != null ? b.LocalName : "bnodevar" + (++bnodectr)));
                }
            }

            model.Query(queryModel.ToArray(), qopts, qs);
        }
        else
        {
            query.Run(model, qs);
        }

        if (qs is IDisposable)
        {
            ((IDisposable)qs).Dispose();
        }
    }
Example #7
0
    static void RunTest(Entity test, Store manifest)
    {
        Entity rdf_type = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
        Entity mf_PositiveSyntaxTest = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#PositiveSyntaxTest";
        Entity mf_NegativeSyntaxTest = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#NegativeSyntaxTest";
        Entity mf_QueryTest          = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#QueryEvaluationTest";
        Entity mf_action             = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#action";
        Entity mf_result             = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#result";
        Entity qt_data  = "http://www.w3.org/2001/sw/DataAccess/tests/test-query#data";
        Entity qt_query = "http://www.w3.org/2001/sw/DataAccess/tests/test-query#query";

        Entity test_type = (Entity)manifest.SelectObjects(test, rdf_type)[0];
        Entity action    = (Entity)manifest.SelectObjects(test, mf_action)[0];

        if (test_type == mf_PositiveSyntaxTest || test_type == mf_NegativeSyntaxTest)
        {
            // The action is a query.

            // Load the action as a string.
            string q = ReadFile(action.Uri);

            // Run the action.
            try {
                new SparqlEngine(q);
            } catch (SemWeb.Query.QueryFormatException qfe) {
                // On a negative test: Good!
                if (test_type == mf_NegativeSyntaxTest)
                {
                    pass++;
                    return;
                }

                Console.WriteLine("Test Failed: " + action);
                Console.WriteLine(qfe.Message);
                Console.WriteLine(q);
                Console.WriteLine();
                fail++;
                return;
            }

            // On a positive test: Good!
            if (test_type == mf_PositiveSyntaxTest)
            {
                pass++;
                return;
            }

            Console.WriteLine("Test Failed: " + action);
            Console.WriteLine("Query is syntactically incorrect.");
            Console.WriteLine(q);
            Console.WriteLine();
            fail++;
        }
        else if (test_type == mf_QueryTest)
        {
            Entity data   = (Entity)manifest.SelectObjects(action, qt_data)[0];
            Entity query  = (Entity)manifest.SelectObjects(action, qt_query)[0];
            Entity result = (Entity)manifest.SelectObjects(test, mf_result)[0];

            MemoryStore data_store = new MemoryStore(new N3Reader(data.Uri));
            string      q          = ReadFile(query.Uri);

            if (q.IndexOf("ASK") >= 0)
            {
                Console.WriteLine("ASK Test Skipped: " + test);
                skip++;
                return;
            }

            string run_individual_test = "mono ../../bin/rdfquery.exe -type sparql n3:" + data.Uri + " < " + query.Uri;

            SparqlEngine sp;
            try {
                sp = new SparqlEngine(q);
            } catch (SemWeb.Query.QueryFormatException qfe) {
                Console.WriteLine("Test Failed: " + test);
                Console.WriteLine(run_individual_test);
                Console.WriteLine(q);
                Console.WriteLine(qfe.Message);
                Console.WriteLine();
                fail++;
                return;
            }

            QueryResultBuffer results = new QueryResultBuffer();
            bool results_bool         = false;
            try {
                if (sp.Type != SparqlEngine.QueryType.Ask)
                {
                    sp.Run(data_store, results);
                }
                else
                {
                    results_bool = sp.Ask(data_store);
                }
            } catch (Exception e) {
                Console.WriteLine("Test Failed: " + test);
                Console.WriteLine(run_individual_test);
                Console.WriteLine(q);
                Console.WriteLine(e);
                Console.WriteLine();
                fail++;
                return;
            }

            bool          failed = false;
            StringBuilder info   = new StringBuilder();

            if (result.Uri.EndsWith(".ttl") || result.Uri.EndsWith(".srx") || result.Uri.EndsWith(".rdf"))
            {
                bool sorted = false;
                QueryResultBuffer results2 = new QueryResultBuffer();

                if (result.Uri.EndsWith(".srx"))
                {
                    using (FileStream fs = new FileStream(result.Uri, FileMode.Open))
                        SemWeb.Remote.SparqlHttpSource.ParseSparqlResponse(fs, results2);
                }
                else if (result.Uri.EndsWith(".rdf") || result.Uri.EndsWith(".ttl"))
                {
                    RdfReader reader = null;
                    if (result.Uri.EndsWith(".rdf"))
                    {
                        reader = new RdfXmlReader(result.Uri);
                    }
                    else if (result.Uri.EndsWith(".ttl"))
                    {
                        reader = new N3Reader(result.Uri);
                    }
                    MemoryStore result_store = new MemoryStore(reader);

                    string rs               = "http://www.w3.org/2001/sw/DataAccess/tests/result-set#";
                    Entity rsResultSet      = rs + "ResultSet";
                    Entity rsresultVariable = rs + "resultVariable";
                    Entity rssolution       = rs + "solution";
                    Entity rsindex          = rs + "index";
                    Entity rsbinding        = rs + "binding";
                    Entity rsvariable       = rs + "variable";
                    Entity rsvalue          = rs + "value";

                    // get a list of variables in the query output
                    Entity    resultset = result_store.GetEntitiesOfType(rsResultSet)[0];
                    ArrayList vars      = new ArrayList();
                    foreach (Literal var in result_store.SelectObjects(resultset, rsresultVariable))
                    {
                        vars.Add(new Variable(var.Value));
                    }
                    Variable[] varsarray = (Variable[])vars.ToArray(typeof(Variable));

                    // try to order as best we can to our own output, so we sort the results the same way
                    for (int i = 0; i < results.Variables.Length; i++)
                    {
                        if (i >= varsarray.Length)
                        {
                            break;
                        }
                        for (int j = i; j < varsarray.Length; j++)
                        {
                            if (varsarray[j].LocalName == results.Variables[i].LocalName)
                            {
                                Variable temp = varsarray[i];
                                varsarray[i] = varsarray[j];
                                varsarray[j] = temp;
                                break;
                            }
                        }
                    }

                    Hashtable varmap = new Hashtable();
                    foreach (Variable v in varsarray)
                    {
                        varmap[v.LocalName] = varmap.Count;
                    }

                    results2.Init(varsarray);

                    Resource[] resultbindings = result_store.SelectObjects(resultset, rssolution);

                    // Try sorting by index
                    int[] indexes = new int[resultbindings.Length];
                    for (int i = 0; i < resultbindings.Length; i++)
                    {
                        Entity  binding = (Entity)resultbindings[i];
                        Literal index   = (Literal)result_store.SelectObjects(binding, rsindex)[0];
                        indexes[i] = (int)(Decimal)index.ParseValue();
                        sorted     = true;
                    }
                    Array.Sort(indexes, resultbindings);

                    // Add bindings into results2.
                    for (int i = 0; i < resultbindings.Length; i++)
                    {
                        Resource[] row     = new Resource[vars.Count];
                        Entity     binding = (Entity)resultbindings[i];
                        foreach (Entity var in result_store.SelectObjects(binding, rsbinding))
                        {
                            string   name = ((Literal)result_store.SelectObjects(var, rsvariable)[0]).Value;
                            Resource val  = result_store.SelectObjects(var, rsvalue)[0];
                            row[(int)varmap[name]] = val;
                        }
                        results2.Add(new VariableBindings(varsarray, row));
                    }
                }

                // Check variable list
                ArrayList vars1 = new ArrayList();
                foreach (Variable v in results.Variables)
                {
                    vars1.Add(v.LocalName);
                }
                ArrayList vars2 = new ArrayList();
                foreach (Variable v in results2.Variables)
                {
                    vars2.Add(v.LocalName);
                }
                failed |= !SetsSame(vars1, vars2, "Result Set Variables", info);

                // Checking bindings
                if (results.Bindings.Count != results2.Bindings.Count)
                {
                    info.Append("Solutions have different number of bindings.\n");
                    failed = true;
                }
                else
                {
                    // Now actually run comparison.

                    if (!sorted)
                    {
                        ((ArrayList)results.Bindings).Sort();
                        ((ArrayList)results2.Bindings).Sort();
                    }

                    for (int i = 0; i < results.Bindings.Count; i++)
                    {
                        VariableBindings b1 = (VariableBindings)results.Bindings[i];
                        VariableBindings b2 = (VariableBindings)results2.Bindings[i];
                        foreach (Variable var in results.Variables)
                        {
                            Resource val1 = b1[var.LocalName];
                            Resource val2 = b2[var.LocalName];
                            if (val1 != val2 && !(val1 is BNode) && !(val2 is BNode))                                       // TODO: Test bnodes are returned correctly
                            {
                                info.Append("Binding row " + i + " differ in value of " + var.LocalName + " variable: " + val2 + ", should be: " + val1 + "\n");
                                failed = true;
                            }
                        }
                    }
                }
            }
            else
            {
                skip++;
                Console.WriteLine(test + ": Unknown result type " + result.Uri);
            }

            if (failed)
            {
                Console.WriteLine("Test Failed: " + test);
                Console.WriteLine(run_individual_test);
                Console.WriteLine(q);
                Console.WriteLine(info.ToString());
                Console.WriteLine();
                fail++;
            }
            else
            {
                pass++;
            }
        }
        else
        {
            skip++;
            Console.WriteLine(test + ": Unknown test type " + test_type);
            Console.WriteLine();
        }
    }
Example #8
0
        private static void ProcessResponse(string mimetype, Stream stream, object outputObj)
        {
            // If the user wants the output sent to a TextWriter, copy the response from
            // the response stream to the TextWriter. TODO: Get encoding from HTTP header.
            if (outputObj is TextWriter)
            {
                TextWriter tw = (TextWriter)outputObj;
                using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8)) {
                    char[] buffer = new char[512];
                    while (true)
                    {
                        int len = reader.Read(buffer, 0, buffer.Length);
                        if (len <= 0)
                        {
                            break;
                        }
                        tw.Write(buffer, 0, len);

                        if (Debug)
                        {
                            Console.Error.WriteLine(">> " + new String(buffer, 0, len));
                        }
                    }
                }
                tw.Flush();
                return;
            }

            // If the user wants a boolean out of this, then we're expecting a
            // SPARQL XML Results document with a boolean response element.
            if (outputObj is BooleanWrap)
            {
                BooleanWrap bw = (BooleanWrap)outputObj;

                if (mimetype != null && mimetype != "application/sparql-results+xml" && mimetype != "text/xml" && mimetype != "application/xml")
                {
                    throw new ApplicationException("The result of the query was not a SPARQL Results document.");
                }

                XmlReader xmldoc = new XmlTextReader(stream);
                {
                    // Move to the document element
                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element)
                        {
                            break;
                        }
                    }

                    // Just check that it has the right local name.
                    if (xmldoc.LocalName != "sparql" || xmldoc.IsEmptyElement)
                    {
                        throw new ApplicationException("Invalid server response: Not a SPARQL results document.");
                    }

                    // Move to the next node.
                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element)
                        {
                            break;
                        }
                    }

                    // If it's a head node, skip it.
                    if (xmldoc.LocalName == "head")
                    {
                        xmldoc.Skip();
                        // Move to the 'boolean' element, it better be next
                        while (xmldoc.Read())
                        {
                            if (xmldoc.NodeType == XmlNodeType.Element)
                            {
                                break;
                            }
                        }
                    }

                    if (xmldoc.LocalName != "boolean")
                    {
                        throw new ApplicationException("Invalid server response: Missing 'boolean' element.");
                    }

                    string value = xmldoc.ReadElementString();
                    bw.value = (value == "true");
                }

                if (Debug)
                {
                    Console.Error.WriteLine(">> " + bw.value);
                }

                return;
            }

            // If the user wants statements out of the response, read it with an RDFReader.
            if (outputObj is StatementSink)
            {
                // If the mime type is application/sparql-results+xml, just try to
                // read it as if it were an RDF/XML MIME type.
                if (mimetype != null && mimetype == "application/sparql-results+xml")
                {
                    mimetype = "text/xml";
                }
                using (RdfReader reader = RdfReader.Create(mimetype, stream))
                    reader.Select((StatementSink)outputObj);
                if (Debug)
                {
                    Console.Error.WriteLine(">> (read as statements)");
                }
                return;
            }

            // If the user wants query result bindings, read the response XML.
            if (outputObj is QueryResultSink)
            {
                QueryResultSink sink = (QueryResultSink)outputObj;

                if (mimetype != null && mimetype != "application/sparql-results+xml" && mimetype != "text/xml")
                {
                    throw new ApplicationException("The result of the query was not a SPARQL Results document.");
                }

                ArrayList  variableNames  = new ArrayList();
                ArrayList  variables      = new ArrayList();
                Variable[] variablesArray = null;
                Hashtable  bnodes         = new Hashtable();

                XmlReader xmldoc = new XmlTextReader(stream);
                {
                    // Move to the document element
                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element)
                        {
                            break;
                        }
                    }

                    // Just check that it has the right local name.
                    if (xmldoc.LocalName != "sparql" || xmldoc.IsEmptyElement)
                    {
                        throw new ApplicationException("Invalid server response: Not a SPARQL results document.");
                    }

                    // Move to the 'head' node, it better be the first element
                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element)
                        {
                            break;
                        }
                    }

                    if (xmldoc.LocalName != "head" || xmldoc.IsEmptyElement)
                    {
                        throw new ApplicationException("Invalid server response: Missing head full element.");
                    }

                    // Read the head element
                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "variable")
                        {
                            if (xmldoc.GetAttribute("name") == null)
                            {
                                throw new ApplicationException("Invalid server response: Head/variable node missing name attribute.");
                            }
                            variableNames.Add(xmldoc.GetAttribute("name"));
                            variables.Add(new Variable(xmldoc.GetAttribute("name")));
                            if (!xmldoc.IsEmptyElement)
                            {
                                xmldoc.Skip();
                            }
                        }
                        else if (xmldoc.NodeType == XmlNodeType.EndElement)
                        {
                            break;
                        }
                    }

                    // Move to the 'results' element, it better be next
                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element)
                        {
                            break;
                        }
                    }

                    if (xmldoc.LocalName != "results")
                    {
                        throw new ApplicationException("Invalid server response: Missing results element.");
                    }

                    variablesArray = (Variable[])variables.ToArray(typeof(Variable));
                    sink.Init(variablesArray);

                    // Read the results

                    while (xmldoc.Read())
                    {
                        if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "result")
                        {
                            // Read the bindings in this result
                            Resource[] valuesArray = new Resource[variablesArray.Length];
                            while (xmldoc.Read())
                            {
                                if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "binding")
                                {
                                    if (xmldoc.IsEmptyElement)
                                    {
                                        throw new ApplicationException("Invalid server response: Binding element empty.");
                                    }
                                    if (xmldoc.GetAttribute("name") == null)
                                    {
                                        throw new ApplicationException("Invalid server response: Result binding node missing name attribute.");
                                    }
                                    int vIndex = variableNames.IndexOf(xmldoc.GetAttribute("name"));
                                    if (vIndex == -1)
                                    {
                                        throw new ApplicationException("Invalid server response: Result binding name does not match a variable in the head.");
                                    }

                                    Resource value = null;

                                    while (xmldoc.Read())
                                    {
                                        if (xmldoc.NodeType == XmlNodeType.Whitespace || xmldoc.NodeType == XmlNodeType.SignificantWhitespace)
                                        {
                                            continue;
                                        }
                                        if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "uri")
                                        {
                                            value = new Entity(xmldoc.ReadElementString());
                                            if (!xmldoc.IsEmptyElement)
                                            {
                                                xmldoc.Skip();
                                            }
                                        }
                                        else if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "literal")
                                        {
                                            string lang = xmldoc.XmlLang;
                                            if (lang == "")
                                            {
                                                lang = null;
                                            }
                                            string dt = xmldoc.GetAttribute("datatype");
                                            value = new Literal(xmldoc.ReadElementString(), lang, dt);
                                            if (!xmldoc.IsEmptyElement)
                                            {
                                                xmldoc.Skip();
                                            }
                                        }
                                        else if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "bnode")
                                        {
                                            string id = xmldoc.ReadElementString();
                                            if (bnodes.ContainsKey(id))
                                            {
                                                value = (BNode)bnodes[id];
                                            }
                                            else
                                            {
                                                value      = new BNode(id);
                                                bnodes[id] = value;
                                            }
                                            if (!xmldoc.IsEmptyElement)
                                            {
                                                xmldoc.Skip();
                                            }
                                        }
                                        else
                                        {
                                            throw new ApplicationException("Invalid server response: Invalid content in binding node.");
                                        }
                                        break;
                                    }
                                    if (value == null)
                                    {
                                        throw new ApplicationException("Invalid server response: Result binding value is invalid.");
                                    }

                                    valuesArray[vIndex] = value;
                                }
                                else if (xmldoc.NodeType == XmlNodeType.EndElement)
                                {
                                    break;
                                }
                            }

                            sink.Add(new VariableBindings(variablesArray, valuesArray));
                            if (Debug)
                            {
                                Console.Error.WriteLine(">> " + new VariableBindings(variablesArray, valuesArray));
                            }
                        }
                        else if (xmldoc.NodeType == XmlNodeType.EndElement)
                        {
                            break;
                        }
                    }

                    sink.Finished();
                }
            }
        }
 public void Should_use_RDF_reader()
 {
     RdfReader.Verify(instance => instance.Read(StreamReader), Times.Once);
 }
Example #10
0
		
		public void Add(string uri, RdfReader source) {
			MemoryStore store = new MemoryStore(source);
			Add(uri, store);
Example #11
0
		
		public void Add(RdfReader source) {
			MemoryStore store = new MemoryStore(source);
			Add(store);
 public KnowledgeModel(RdfReader parser) : this()
 {
     stores.Add(new MemoryStore(parser));
 }
Example #13
0
        public void Add(string uri, RdfReader source)
        {
            MemoryStore store = new MemoryStore(source);

            Add(uri, store);
        }
Example #14
0
        public void Add(RdfReader source)
        {
            MemoryStore store = new MemoryStore(source);

            Add(store);
        }
Example #15
0
    static void RunTest(Store testlist, Entity test, bool shouldSucceed, int mode)
    {
        string inputpath = null, outputpath = null,
               inputformat = null, outputformat = null,
               inputbase = null, outputbase = null;

        if (mode == 0)
        {
            inputformat  = "xml";
            outputformat = "n3";

            string   uribase = "http://www.w3.org/2000/10/rdf-tests/rdfcore/";
            Resource input   = testlist.SelectObjects(test, "http://www.w3.org/2000/10/rdf-tests/rdfcore/testSchema#inputDocument")[0];
            inputbase = input.Uri;
            inputpath = input.Uri.Substring(uribase.Length);

            if (testlist.SelectObjects(test, "http://www.w3.org/2000/10/rdf-tests/rdfcore/testSchema#outputDocument").Length > 0)
            {
                Resource output = testlist.SelectObjects(test, "http://www.w3.org/2000/10/rdf-tests/rdfcore/testSchema#outputDocument")[0];
                outputpath = output.Uri.Substring(uribase.Length);
                outputbase = output.Uri;
            }
        }
        else if (mode == 1)
        {
            inputformat  = "n3";
            outputformat = "n3";
            inputbase    = "file:/home/syosi/cvs-trunk/WWW/2000/10/swap/test/n3parser.tests";

            string uribase = "http://www.example.org/";

            if (testlist.SelectObjects(test, "http://www.w3.org/2004/11/n3test#inputDocument").Length == 0)
            {
                return;
            }
            Resource input = testlist.SelectObjects(test, "http://www.w3.org/2004/11/n3test#inputDocument")[0];
            inputpath = input.Uri.Substring(uribase.Length);

            if (testlist.SelectObjects(test, "http://www.w3.org/2004/11/n3test#outputDocument").Length > 0)
            {
                Resource output = testlist.SelectObjects(test, "http://www.w3.org/2004/11/n3test#outputDocument")[0];
                outputpath = output.Uri.Substring(uribase.Length);
            }
        }


        string desc = test.ToString();

        try {
            desc += " " + ((Literal)testlist.SelectObjects(test, "http://www.w3.org/2000/10/rdf-tests/rdfcore/testSchema#description")[0]).Value;
        } catch (Exception e) {
        }

        try {
            total++;

            RdfReader reader = RdfReader.Create(inputformat, Path.Combine(basepath, inputpath));
            reader.BaseUri = inputbase;

            MemoryStore inputmodel = new MemoryStore(reader);
            if (reader.Warnings.Count > 0)
            {
                string warnings = String.Join("; ", (string[])((ArrayList)reader.Warnings).ToArray(typeof(string)));
                throw new ParserException(warnings);
            }
            if (!shouldSucceed)
            {
                Console.WriteLine(desc + ": Should Not Have Passed **\n");
                badpass++;
                return;
            }

            if (shouldSucceed && outputpath != null)
            {
                RdfReader reader2 = RdfReader.Create(outputformat, Path.Combine(basepath, outputpath));
                reader2.BaseUri = outputbase;
                MemoryStore outputmodel = new MemoryStore(reader2);

                CompareModels(inputmodel, outputmodel);
            }
        } catch (System.IO.FileNotFoundException ex) {
            Console.WriteLine(inputpath + " Not Found");
            error++;
        } catch (System.IO.DirectoryNotFoundException ex) {
            Console.WriteLine(inputpath + " Not Found");
            error++;
        } catch (ParserException ex) {
            if (shouldSucceed)
            {
                Console.WriteLine(desc + ": " + ex.Message + " **");
                Console.WriteLine();
                badfail++;
            }
        }
    }
Example #16
0
 public GraphMatch(RdfReader query) :
     this(new MemoryStore(query),
          query.BaseUri == null ? null : new Entity(query.BaseUri))
 {
 }