public static void Main(String[] args) 
    {
	    //Fill in the code shown on this page here to build your hello world application
        Graph g = new Graph();

        IUriNode dotNetRDF = g.CreateUriNode(new Uri("http://www.dotnetrdf.org"));
        IUriNode says = g.CreateUriNode(new Uri("http://example.org/says"));
        ILiteralNode helloWorld = g.CreateLiteralNode("Hello World");
        ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr");

        g.Assert(new Triple(dotNetRDF, says, helloWorld));
        g.Assert(new Triple(dotNetRDF, says, bonjourMonde));

        foreach (Triple t in g.Triples)
        {
            Console.WriteLine(t.ToString());
        }

        NTriplesWriter ntwriter = new NTriplesWriter();
        ntwriter.Save(g, "HelloWorld.nt");

        RdfXmlWriter rdfxmlwriter = new RdfXmlWriter();
        rdfxmlwriter.Save(g, "HelloWorld.rdf");

    }
Example #2
0
        public void WritingNTriplesCharEscaping()
        {
            TurtleParser   parser   = new TurtleParser();
            NTriplesParser ntparser = new NTriplesParser();
            NTriplesWriter ntwriter = new NTriplesWriter();

            foreach (String sample in samples)
            {
                Graph g = new Graph();
                Console.WriteLine("Original RDF Fragment");
                Console.WriteLine(prefix + sample);
                StringParser.Parse(g, prefix + sample, parser);
                Console.WriteLine();
                Console.WriteLine("Triples in Original");
                foreach (Triple t in g.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
                Console.WriteLine();

                String serialized = VDS.RDF.Writing.StringWriter.Write(g, ntwriter);
                Console.WriteLine("Serialized RDF Fragment");
                Console.WriteLine(serialized);

                Graph h = new Graph();
                StringParser.Parse(h, serialized, ntparser);

                Console.WriteLine();
                Console.WriteLine("Triples in Serialized");
                foreach (Triple t in g.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
                Console.WriteLine();

                Assert.AreEqual(g, h, "Graphs should have been equal");

                Console.WriteLine("Graphs were equal as expected");
                Console.WriteLine();
            }
        }
Example #3
0
        public static void Main(String[] args)
        {
            try
            {
                Console.WriteLine("Reading a RDF/XML format Test Graph");
                RdfXmlParser parser = new RdfXmlParser();
                Graph g = new Graph();
                parser.Load(g, "JSONTest.rdf");

                Console.WriteLine("Serializing back to RDF/JSON");
                RdfJsonWriter writer = new RdfJsonWriter();
                writer.Save(g, "JSONTest.rdf.json");

                Console.WriteLine("Reading back from the RDF/JSON");
                RdfJsonParser jsonparser = new RdfJsonParser();
                Graph h = new Graph();
                jsonparser.Load(h, "JSONTest.rdf.json");

                Console.WriteLine("Outputting to NTriples");
                NTriplesWriter ntwriter = new NTriplesWriter();
                ntwriter.Save(h, "JSONTest.rdf.json.out");

                Console.WriteLine("Reading a RDF/JSON format Test Graph with tons of Comments in it");
                Graph i = new Graph();
                jsonparser.Load(i, "JSONTest.json");

                Console.WriteLine("Outputting to NTriples");
                ntwriter.Save(i, "JSONTest.json.out");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);
                    Console.WriteLine(ex.InnerException.StackTrace);
                }
            }
        }
        /// <summary>
        /// Updates the underlying store with this as the new representation of the identified resource
        /// </summary>
        /// <param name="resourceUri">The resource for whom this is the representation</param>
        /// <param name="resourceDescription">The rdf xml document that describes the resource</param>
        public override void ApplyFragment(string resourceUri, XDocument resourceDescription)
        {
            try
            {
                var g = new Graph();
                var rdfXmlParser = new RdfXmlParser();
                rdfXmlParser.Load(g, new StringReader(resourceDescription.ToString()));
                var ntWriter = new NTriplesWriter();
                var data = StringWriter.Write(g, ntWriter);

                var sparqlUpdate = "";
                sparqlUpdate += "DELETE { GRAPH <" + GraphUri + "> { <" + resourceUri + ">  ?x  ?y }}";
                sparqlUpdate += "USING <" + GraphUri + "> WHERE {<" + resourceUri + "> ?x ?y } ;";
                sparqlUpdate += "INSERT DATA { GRAPH <" + GraphUri + "> {  ";
                sparqlUpdate += data;
                sparqlUpdate += " }};";

                // execute update
                var wr = WebRequest.Create(SparqlEndpoint) as HttpWebRequest;
                wr.ContentType = "application/sparql-update";
                wr.Method = "POST";
                var ds = wr.GetRequestStream();
                var bytes = Encoding.ASCII.GetBytes(sparqlUpdate);
                ds.Write(bytes, 0, bytes.Length);
                var resp = wr.GetResponse() as HttpWebResponse;

                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    Logging.LogDebug("Update successful");
                }
                else
                {
                    Logging.LogDebug("Not a 200");
                }
                resp.Close();
            } catch(Exception ex)
            {
                Logging.LogError(1, "Unable to apply fragment for resourceUri {0} {1}", ex.Message, ex.StackTrace);
            }
        }
Example #5
0
        public void WritingNTriplesCharEscaping()
        {
            TurtleParser parser = new TurtleParser();
            NTriplesParser ntparser = new NTriplesParser();
            NTriplesWriter ntwriter = new NTriplesWriter();

            foreach (String sample in samples)
            {
                Graph g = new Graph();
                Console.WriteLine("Original RDF Fragment");
                Console.WriteLine(prefix + sample);
                StringParser.Parse(g, prefix + sample, parser);
                Console.WriteLine();
                Console.WriteLine("Triples in Original");
                foreach (Triple t in g.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
                Console.WriteLine();

                String serialized = StringWriter.Write(g, ntwriter);
                Console.WriteLine("Serialized RDF Fragment");
                Console.WriteLine(serialized);

                Graph h = new Graph();
                StringParser.Parse(h, serialized, ntparser);

                Console.WriteLine();
                Console.WriteLine("Triples in Serialized");
                foreach (Triple t in g.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
                Console.WriteLine();

                Assert.AreEqual(g, h, "Graphs should have been equal");

                Console.WriteLine("Graphs were equal as expected");
                Console.WriteLine();
            }
        }
        /// <summary>
        /// Updates a Graph
        /// </summary>
        /// <param name="graphUri">Uri of the Graph to update</param>
        /// <param name="additions">Triples to be added</param>
        /// <param name="removals">Triples to be removed</param>
        public virtual void UpdateGraph(String graphUri, IEnumerable<Triple> additions, IEnumerable<Triple> removals)
        {
            try
            {
                HttpWebRequest request;
                HttpWebResponse response;
                Dictionary<String, String> serviceParams = new Dictionary<string, string>();
                NTriplesWriter ntwriter = new NTriplesWriter();
                //RdfXmlWriter writer = new RdfXmlWriter();

                if (!graphUri.Equals(String.Empty))
                {
                    serviceParams.Add("context", "<" + graphUri + ">");
                }
                else
                {
                    serviceParams.Add("context", "null");
                }

                if (removals != null)
                {
                    if (removals.Any())
                    {
                        serviceParams.Add("subj", null);
                        serviceParams.Add("pred", null);
                        serviceParams.Add("obj", null);

                        //Have to do a DELETE for each individual Triple
                        foreach (Triple t in removals.Distinct())
                        {
                            this._output.Remove(0, this._output.Length);
                            serviceParams["subj"] = this._formatter.Format(t.Subject);
                            serviceParams["pred"] = this._formatter.Format(t.Predicate);
                            serviceParams["obj"] = this._formatter.Format(t.Object);
                            request = this.CreateRequest(this._repositoriesPrefix + this._store + "/statements", "*/*", "DELETE", serviceParams);

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

                            using (response = (HttpWebResponse)request.GetResponse())
                            {
            #if DEBUG
                                if (Options.HttpDebugging)
                                {
                                    Tools.HttpDebugResponse(response);
                                }
            #endif
                                //If we get here then the Delete worked OK
                                response.Close();
                            }
                        }
                        serviceParams.Remove("subj");
                        serviceParams.Remove("pred");
                        serviceParams.Remove("obj");
                    }
                }

                if (additions != null)
                {
                    if (additions.Any())
                    {
                        //Add the new Triples
                        request = this.CreateRequest(this._repositoriesPrefix + this._store + "/statements", "*/*", "POST", serviceParams);
                        Graph h = new Graph();
                        h.Assert(additions);
                        request.ContentType = MimeTypesHelper.NTriples[0];
                        ntwriter.Save(h, new StreamWriter(request.GetRequestStream()));
                        //request.ContentType = MimeTypesHelper.RdfXml[0];
                        //writer.Save(h, new StreamWriter(request.GetRequestStream()));

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

                        using (response = (HttpWebResponse)request.GetResponse())
                        {
            #if DEBUG
                            if (Options.HttpDebugging)
                            {
                                Tools.HttpDebugResponse(response);
                            }
            #endif
                            //If we get then it was OK
                            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 update a Graph in the Store", webEx);
            }
        }
        /// <summary>
        /// Saves a Graph into the Store (Warning: Completely replaces any existing Graph with the same URI unless there is no URI - see remarks for details)
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <remarks>
        /// If the Graph has no URI then the contents will be appended to the Store, if the Graph has a URI then existing data associated with that URI will be replaced
        /// </remarks>
        public virtual void SaveGraph(IGraph g)
        {
            try
            {
                HttpWebRequest request;
                Dictionary<String, String> serviceParams = new Dictionary<string, string>();

                if (g.BaseUri != null)
                {
                    if (this._fullContextEncoding)
                    {
                        serviceParams.Add("context", "<" + g.BaseUri.ToString() + ">");
                    }
                    else
                    {
                        serviceParams.Add("context", g.BaseUri.ToString());
                    }
                    request = this.CreateRequest(this._repositoriesPrefix + this._store + "/statements", "*/*", "PUT", serviceParams);
                }
                else
                {
                    request = this.CreateRequest(this._repositoriesPrefix + this._store + "/statements", "*/*", "POST", serviceParams);
                }

                request.ContentType = MimeTypesHelper.NTriples[0];
                NTriplesWriter ntwriter = new NTriplesWriter();
                ntwriter.Save(g, new StreamWriter(request.GetRequestStream()));

                //request.ContentType = MimeTypesHelper.RdfXml[0];
                //RdfXmlWriter writer = new RdfXmlWriter();
                //writer.Save(g, new StreamWriter(request.GetRequestStream()));

            #if DEBUG
                if (Options.HttpDebugging)
                {
                    Tools.HttpDebugRequest(request);
                }
            #endif
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
            #if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
            #endif
                    //If we get then it was OK
                    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 save a Graph to the Store", webEx);
            }
        }
        /// <summary>
        /// Deletes a Graph from the Sesame store
        /// </summary>
        /// <param name="graphUri">URI of the Graph to delete</param>
        public virtual void DeleteGraph(String graphUri)
        {
            try
            {
                HttpWebRequest request;
                HttpWebResponse response;
                Dictionary<String, String> serviceParams = new Dictionary<string, string>();
                NTriplesWriter ntwriter = new NTriplesWriter();

                if (!graphUri.Equals(String.Empty))
                {
                    serviceParams.Add("context", "<" + graphUri + ">");
                }
                else
                {
                    serviceParams.Add("context", "null");
                }

                request = this.CreateRequest(this._repositoriesPrefix + this._store + "/statements", "*/*", "DELETE", serviceParams);
            #if DEBUG
                if (Options.HttpDebugging)
                {
                    Tools.HttpDebugRequest(request);
                }
            #endif
                using (response = (HttpWebResponse)request.GetResponse())
                {
            #if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
            #endif
                    //If we get here then the Delete worked OK
                    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 delete a Graph from the Store", webEx);
            }
        }
        public static void Main(string[] args)
        {
            StreamWriter output = new StreamWriter("TurtleTestSuite.txt");
            String[] wantTrace = {  };
            String[] wantOutput = {  };
            bool outputAll = true;
            bool traceAll = true;
            String[] skipTests = { };//{ "test-14.ttl", "test-15.ttl", "test-16.ttl" };

            Console.SetOut(output);

            try
            {
                int testsPassed = 0;
                int testsFailed = 0;
                String[] files = Directory.GetFiles("turtle_tests");
                TurtleParser parser = new TurtleParser();
                bool passed, passDesired;
                Graph g = new Graph();
                Stopwatch timer = new Stopwatch();
                long totalTime = 0;
                long totalTriples = 0;

                foreach (String file in files)
                {
                    timer.Reset();

                    if (skipTests.Contains(Path.GetFileName(file)))
                    {
                        output.WriteLine("## Skipping Test of File " + Path.GetFileName(file));
                        output.WriteLine();
                        continue;
                    }

                    if (Path.GetExtension(file) != ".ttl")
                    {
                        continue;
                    }

                    Debug.WriteLine("Testing File " + Path.GetFileName(file));
                    output.WriteLine("## Testing File " + Path.GetFileName(file));
                    output.WriteLine("# Test Started at " + DateTime.Now.ToString(TestSuite.TestSuiteTimeFormat));

                    passed = false;
                    passDesired = true;

                    try
                    {
                        g = new Graph();
                        g.BaseUri = new Uri(TestSuiteBaseUri);
                        if (Path.GetFileNameWithoutExtension(file).StartsWith("bad"))
                        {
                            passDesired = false;
                            output.WriteLine("# Desired Result = Parsing Failed");
                        }
                        else
                        {
                            output.WriteLine("# Desired Result = Parses OK");
                        }

                        if (traceAll || wantTrace.Contains(Path.GetFileName(file)))
                        {
                            parser.TraceTokeniser = true;
                        }
                        else
                        {
                            parser.TraceTokeniser = false;
                        }

                        timer.Start();
                        parser.Load(g, file);
                        timer.Stop();

                        Console.WriteLine("Parsing took " + timer.ElapsedMilliseconds + "ms");

                        passed = true;
                        output.WriteLine("Parsed OK");

                        if (outputAll || wantOutput.Contains(Path.GetFileName(file)))
                        {
                            NTriplesWriter writer = new NTriplesWriter();
                            writer.Save(g, "turtle_tests\\" + Path.GetFileNameWithoutExtension(file) + ".out");
                        }

                    }
                    catch (IOException ioEx)
                    {
                        reportError(output, "IO Exception", ioEx);
                    }
                    catch (RdfParseException parseEx)
                    {
                        reportError(output, "Parsing Exception", parseEx);
                    }
                    catch (RdfException rdfEx)
                    {
                        reportError(output, "RDF Exception", rdfEx);
                    }
                    catch (Exception ex)
                    {
                        reportError(output, "Other Exception", ex);
                    }
                    finally
                    {
                        timer.Stop();
                        if (passed && passDesired)
                        {
                            //Passed and we wanted to Pass
                            testsPassed++;
                            output.WriteLine("# Result = Test Passed");
                            totalTime += timer.ElapsedMilliseconds;
                            totalTriples += g.Triples.Count;
                        }
                        else if (!passed && passDesired)
                        {
                            //Failed when we should have Passed
                            testsFailed++;
                            output.WriteLine("# Result = Test Failed");
                        }
                        else if (passed && !passDesired)
                        {
                            //Passed when we should have Failed
                            testsFailed++;
                            output.WriteLine("# Result = Test Failed");
                        }
                        else
                        {
                            //Failed and we wanted to Fail
                            testsPassed++;
                            output.WriteLine("# Result = Test Passed");
                        }

                        output.WriteLine("# Triples Generated = " + g.Triples.Count());
                        output.WriteLine("# Test Ended at " + DateTime.Now.ToString(TestSuite.TestSuiteTimeFormat));
                    }

                    output.WriteLine();
                }

                output.WriteLine(testsPassed + " Tests Passed");
                output.WriteLine(testsFailed + " Tests Failed");
                output.WriteLine();
                output.Write("Total Parsing Time was " + totalTime + " ms");
                if (totalTime > 1000)
                {
                    output.WriteLine(" (" + totalTime / 1000d + " seconds)");
                }
                output.WriteLine("Average Parsing Speed was " + totalTriples / (totalTime / 1000d) + " triples/second");

            }
            catch (Exception ex)
            {
                reportError(output, "Other Exception", ex);
            }

            Console.SetOut(Console.Out);
            Console.WriteLine("Done");
            Debug.WriteLine("Finished");

            output.Close();

        }
Example #10
0
 public void WriteToNTriples(IList<RDFTriple> triples, string outputFile)
 {
     Graph graph = CreateGraph(triples);
     var ntwriter = new NTriplesWriter();
     ntwriter.Save(graph, outputFile);
 }
        public static void Main(string[] args)
        {
            StreamWriter output = new StreamWriter("RdfXmlTestSuite.txt");
            Console.SetOut(output);

            try
            {
                int testsPassed = 0;
                int testsFailed = 0;
                bool passed, passDesired;

                //RdfXmlParser parser = new RdfXmlParser(RdfXmlParserMode.Streaming);
                RdfXmlParser parser = new RdfXmlParser(RdfXmlParserMode.DOM);
                NTriplesWriter ntwriter = new NTriplesWriter();
                parser.TraceParsing = true;
                Graph g = new Graph();

                output.WriteLine("## RDF/XML Test Suite");
                output.WriteLine();

                String[] dirs = Directory.GetDirectories("xmlrdf_tests");

                foreach (String dir in dirs)
                {
                    if (dir.Contains(".svn"))
                    {
                        continue;
                    }
                    String[] files = Directory.GetFiles(dir);

                    foreach (String file in files)
                    {
                        if (!Path.GetExtension(file).Equals(".rdf"))
                        {
                            continue;
                        }

                        passed = false;
                        passDesired = true;

                        output.WriteLine("## Testing " + file);
                        output.WriteLine("# Test Started at " + DateTime.Now.ToString(TestSuite.TestSuiteTimeFormat));

                        if (Path.GetFileNameWithoutExtension(file).StartsWith("error"))
                        {
                            passDesired = false;
                            output.WriteLine("# Desired Result = Parsing Failed");
                        }
                        else
                        {
                            output.WriteLine("# Desired Result = Parses OK");
                        }

                        try
                        {
                            Debug.WriteLine("Testing file " + file);
                            g = new Graph();
                            g.BaseUri = new Uri(XMLTestSuiteBaseURI);
                            parser.Load(g, file);

                            passed = true;
                        }
                        catch (IOException ioEx)
                        {
                            reportError(output, "IO Exception", ioEx);
                        }
                        catch (RdfParseException parseEx)
                        {
                            reportError(output, "Parsing Exception", parseEx);
                        }
                        catch (RdfException rdfEx)
                        {
                            reportError(output, "RDF Exception", rdfEx);
                        }
                        catch (Exception ex)
                        {
                            reportError(output, "Other Exception", ex);
                        }
                        finally
                        {
                            if (passed && passDesired)
                            {
                                //Passed and we wanted to Pass
                                testsPassed++;
                                output.WriteLine("# Result = Test Passed");

                                //Try to write output
                                ntwriter.Save(g, Path.ChangeExtension(file, "out"));
                            }
                            else if (!passed && passDesired)
                            {
                                //Failed when we should have Passed
                                testsFailed++;
                                output.WriteLine("# Result = Test Failed");

                                //Show output
                                output.WriteLine("Generated the following Triples before failing:");
                                foreach (Triple t in g.Triples)
                                {
                                    Console.WriteLine(t.ToString());
                                }
                            }
                            else if (passed && !passDesired)
                            {
                                //Passed when we should have Failed
                                testsFailed++;
                                output.WriteLine("# Result = Test Failed");
                            }
                            else
                            {
                                //Failed and we wanted to Fail
                                testsPassed++;
                                output.WriteLine("# Result = Test Passed");
                            }

                            output.WriteLine("# " + g.Triples.Count() + " Triples generated");
                            output.WriteLine("# Test Ended at " + DateTime.Now.ToString(TestSuite.TestSuiteTimeFormat));

                        }

                        output.WriteLine();
                    }
                }

                output.WriteLine(testsPassed + " Tests Passed");
                output.WriteLine(testsFailed + " Tests Failed");
            }
            catch (IOException ioEx)
            {
                reportError(output, "IO Exception", ioEx);
            }
            catch (RdfParseException parseEx)
            {
                reportError(output, "Parsing Exception", parseEx);
            }
            catch (RdfException rdfEx)
            {
                reportError(output, "RDF Exception", rdfEx);
            }
            catch (Exception ex)
            {
                reportError(output, "Other Exception", ex);
            }

            output.Close();
        }
        public void DeleteGraph(String graphUri)
        {
            try
            {
                HttpWebRequest request;
                HttpWebResponse response;
                Dictionary<String, String> serviceParams = new Dictionary<string, string>();
                NTriplesWriter ntwriter = new NTriplesWriter();

                if (!graphUri.Equals(String.Empty))
                {
                    serviceParams.Add("context", "<" + graphUri + ">");
                }
                else
                {
                    serviceParams.Add("context", "null");
                }

                request = this.CreateRequest("repositories/" + this._store + "/statements", "*/*", "DELETE", serviceParams);
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    //If we get here then the Delete worked OK
                    response.Close();
                }
            }
            catch (WebException webEx)
            {
                throw new RdfStorageException("A HTTP Error occurred while trying to delete a Graph from the Store", webEx);
            }
        }
        /// <summary>
        /// Saves a Graph into the Store (Warning: Completely replaces any existing Graph with the same URI unless there is no URI - see remarks for details)
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <remarks>
        /// If the Graph has no URI then the contents will be appended to the Store, if the Graph has a URI then existing data associated with that URI will be replaced
        /// </remarks>
        public void SaveGraph(IGraph g)
        {
            try
            {
                HttpWebRequest request;
                Dictionary<String, String> serviceParams = new Dictionary<string, string>();

                if (g.BaseUri != null)
                {
                    serviceParams.Add("context", "<" + g.BaseUri.ToString() + ">");
                    request = this.CreateRequest("repositories/" + this._store + "/statements", "*/*", "PUT", serviceParams);
                }
                else
                {
                    request = this.CreateRequest("repositories/" + this._store + "/statements", "*/*", "POST", serviceParams);
                }

                request.ContentType = MimeTypesHelper.NTriples[0];
                NTriplesWriter ntwriter = new NTriplesWriter();
                ntwriter.Save(g, new StreamWriter(request.GetRequestStream()));

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                //If we get then it was OK
                response.Close();
            }
            catch (WebException webEx)
            {
                throw new RdfStorageException("A HTTP Error occurred while trying to save a Graph to the Store", webEx);
            }
        }
Example #14
0
        public void Dispose()
        {
            //Create all of the directories required for the file
            var f = new FileInfo(_outputPath);
            f.Directory.Create();

            if (this._outputFormat == ERdfFormat.RdfXml)
            {
                using (XmlTextWriter xmlWriter = new XmlTextWriter(_outputPath, new UTF8Encoding(false)))
                    //Set encoding
                {
                    _output.Save(xmlWriter);
                }
            }
            else if (this._outputFormat == ERdfFormat.TriG)
            {
                string fileNameAsTrig = GetFilePathBasedOnFormat();
                var outparams = new StreamParams(fileNameAsTrig);
                outparams.Encoding = Encoding.UTF8;
                var writer = new TriGWriter();

                if (_store == null)
                {
                    var g = GetXmlDocumentAsGraph();
                    _store = new TripleStore();
                    _store.Add(g, true);
                }

                writer.Save(_store, outparams);
            }
            else if (this._outputFormat == ERdfFormat.Turtle)
            {
                var g = GetXmlDocumentAsGraph();
                string filePathForFormat = GetFilePathBasedOnFormat();
                var writer = new TurtleWriter(TurtleSyntax.W3C);
                writer.Save(g, filePathForFormat);
            }
            else if (this._outputFormat == ERdfFormat.NTriples)
            {
                var g = GetXmlDocumentAsGraph();
                string filePathForFormat = GetFilePathBasedOnFormat();
                var writer = new NTriplesWriter();
                writer.Save(g, filePathForFormat);
            }
            else if (this._outputFormat == ERdfFormat.N3)
            {
                var g = GetXmlDocumentAsGraph();
                string filePathForFormat = GetFilePathBasedOnFormat();
                var writer = new Notation3Writer();
                writer.Save(g, filePathForFormat);
            }
            else if (this._outputFormat == ERdfFormat.NQuads)
            {
                string filePathForFormat = GetFilePathBasedOnFormat();
                var outparams = new StreamParams(filePathForFormat);
                outparams.Encoding = Encoding.UTF8;

                if (_store == null)
                {
                    var g = GetXmlDocumentAsGraph();
                    _store = new TripleStore();
                    _store.Add(g, true);
                }

                var writer = new NQuadsWriter();
                writer.Save(_store, outparams);
            }

            //make sure it's not null - can happen if no graphs have yet to be asserted!!
            if (_store != null)
            {
                foreach (var graph in _store.Graphs)
                {
                    graph.Dispose();
                }
                _store.Dispose();
                GC.Collect();
            }
        }
        public static void Main(string[] args)
        {
            StreamWriter output = new StreamWriter("Notation3TestSuite.txt");
            String[] wantTrace = { };
            bool traceAll = false;
            String[] wantOutput = { "path2.n3" };
            bool outputAll = false;
            String[] skipTests = { };

            Console.SetOut(output);

            try
            {
                int testsPassed = 0;
                int testsFailed = 0;
                String[] files = Directory.GetFiles("n3_tests");
                Notation3Parser parser = new Notation3Parser(TokenQueueMode.QueueAllBeforeParsing);//new Notation3Parser(TokenQueueMode.QueueAllBeforeParsing);
                parser.Warning += reportWarning;
                bool passed, passDesired;
                Graph g = new Graph();

                foreach (String file in files)
                {
                    if (skipTests.Contains(Path.GetFileName(file)))
                    {
                        output.WriteLine("## Skipping Test of File " + Path.GetFileName(file));
                        output.WriteLine();
                        continue;
                    }

                    if (Path.GetExtension(file) != ".n3")
                    {
                        continue;
                    }

                    Debug.WriteLine("Testing File " + Path.GetFileName(file));
                    output.WriteLine("## Testing File " + Path.GetFileName(file));
                    output.WriteLine("# Test Started at " + DateTime.Now.ToString(TestSuite.TestSuiteTimeFormat));

                    passed = false;
                    passDesired = true;

                    try
                    {
                        g = new Graph();
                        g.BaseUri = new Uri(TestSuiteBaseUri);
                        if (Path.GetFileNameWithoutExtension(file).StartsWith("bad"))
                        {
                            passDesired = false;
                            output.WriteLine("# Desired Result = Parsing Failed");
                        }
                        else
                        {
                            output.WriteLine("# Desired Result = Parses OK");
                        }

                        if (wantTrace.Contains(Path.GetFileName(file)) || traceAll)
                        {
                            parser.TraceTokeniser = true;
                        }
                        else
                        {
                            parser.TraceTokeniser = false;
                        }

                        parser.Load(g, file);

                        passed = true;
                        output.WriteLine("Parsed OK");

                        if (outputAll || wantOutput.Contains(Path.GetFileName(file)))
                        {
                            if (!outputAll)
                            {
                                foreach (Triple t in g.Triples)
                                {
                                    Console.WriteLine(t.ToString());
                                }
                            }
                            NTriplesWriter writer = new NTriplesWriter();
                            writer.Save(g, "n3_tests\\" + Path.GetFileNameWithoutExtension(file) + ".out");
                        }

                    }
                    catch (IOException ioEx)
                    {
                        reportError(output, "IO Exception", ioEx);
                    }
                    catch (RdfParseException parseEx)
                    {
                        reportError(output, "Parsing Exception", parseEx);
                    }
                    catch (RdfException rdfEx)
                    {
                        reportError(output, "RDF Exception", rdfEx);
                    }
                    catch (Exception ex)
                    {
                        reportError(output, "Other Exception", ex);
                    }
                    finally
                    {
                        if (passed && passDesired)
                        {
                            //Passed and we wanted to Pass
                            testsPassed++;
                            output.WriteLine("# Result = Test Passed");
                        }
                        else if (!passed && passDesired)
                        {
                            //Failed when we should have Passed
                            testsFailed++;
                            output.WriteLine("# Result = Test Failed");
                        }
                        else if (passed && !passDesired)
                        {
                            //Passed when we should have Failed
                            testsFailed++;
                            output.WriteLine("# Result = Test Failed");
                        }
                        else
                        {
                            //Failed and we wanted to Fail
                            testsPassed++;
                            output.WriteLine("# Result = Test Passed");
                        }

                        output.WriteLine("# Triples Generated = " + g.Triples.Count());
                        output.WriteLine("# Test Ended at " + DateTime.Now.ToString(TestSuite.TestSuiteTimeFormat));
                    }

                    output.WriteLine();
                }

                output.WriteLine(testsPassed + " Tests Passed");
                output.WriteLine(testsFailed + " Tests Failed");

            }
            catch (Exception ex)
            {
                reportError(output, "Other Exception", ex);
            }

            Console.SetOut(Console.Out);
            Console.WriteLine("Done");
            Debug.WriteLine("Finished");

            output.Close();

        }
Example #16
0
        public static void Main(string[] args)
        {
            StreamWriter output = new StreamWriter("RdfATestSuite.txt");
            String[] wantTrace = {  };
            String[] wantOutput = {  };
            bool outputAll = true;
            bool traceAll = false;
            String[] skipTests = { 
                                   "0002.xhtml",
                                   "0003.xhtml", 
                                   "0004.xhtml",
                                   "0005.xhtml",
                                   "0016.xhtml",
                                   "0022.xhtml",
                                   "0024.xhtml",
                                   "0028.xhtml",
                                   "0043.xhtml",
                                   "0044.xhtml",
                                   "0045.xhtml",
                                   "0095.xhtml",
                                   "0096.xhtml",
                                   "0097.xhtml",
                                   "0098.xhtml",
                                   "0122.xhtml",
                                   "0123.xhtml",
                                   "0124.xhtml",
                                   "0125.xhtml",
                                   "0126.xhtml"
                                 };

            String[] skipCheck = {
                                     "0011.xhtml",
                                     "0092.xhtml",
                                     "0094.xhtml",
                                     "0100.xhtml",
                                     "0101.xhtml",
                                     "0102.xhtml",
                                     "0103.xhtml",
                                 };

            String[] falseTests = {
                                    "0042.xhtml",
                                    "0086.xhtml",
                                    "0095.xhtml",
                                    "0096.xhtml",
                                    "0097.xhtml",
                                    "0107.xhtml",
                                    "0116.xhtml",
                                    "0122.xhtml",
                                    "0125.xhtml"
                                  };

            Console.SetOut(output);

            try
            {
                int testsPassed = 0;
                int testsFailed = 0;
                String[] files = Directory.GetFiles("rdfa_tests");
                RdfAParser parser = new RdfAParser(RdfASyntax.AutoDetectLegacy);
                parser.Warning += new RdfReaderWarning(parser_Warning);
                SparqlQueryParser queryparser = new SparqlQueryParser();
                bool passed, passDesired;
                Graph g = new Graph();
                Stopwatch timer = new Stopwatch();
                long totalTime = 0;
                long totalTriples = 0;

                foreach (String file in files)
                {
                    timer.Reset();

                    if (skipTests.Contains(Path.GetFileName(file)))
                    {
                        output.WriteLine("## Skipping Test of File " + Path.GetFileName(file));
                        output.WriteLine();
                        continue;
                    }

                    if (Path.GetExtension(file) != ".html" && Path.GetExtension(file) != ".xhtml")
                    {
                        continue;
                    }

                    Debug.WriteLine("Testing File " + Path.GetFileName(file));
                    output.WriteLine("## Testing File " + Path.GetFileName(file));
                    output.WriteLine("# Test Started at " + DateTime.Now.ToString(TestSuite.TestSuiteTimeFormat));

                    passed = false;
                    passDesired = true;

                    try
                    {
                        g = new Graph();
                        g.BaseUri = new Uri("http://www.w3.org/2006/07/SWD/RDFa/testsuite/xhtml1-testcases/" + Path.GetFileName(file));
                        if (Path.GetFileNameWithoutExtension(file).StartsWith("bad"))
                        {
                            passDesired = false;
                            output.WriteLine("# Desired Result = Parsing Failed");
                        }
                        else
                        {
                            output.WriteLine("# Desired Result = Parses OK");
                        }

                        //if (traceAll || wantTrace.Contains(Path.GetFileName(file)))
                        //{
                        //    parser.TraceTokeniser = true;
                        //}
                        //else
                        //{
                        //    parser.TraceTokeniser = false;
                        //}

                        timer.Start();
                        parser.Load(g, file);
                        timer.Stop();

                        Console.WriteLine("Parsing took " + timer.ElapsedMilliseconds + "ms");

                        passed = true;
                        output.WriteLine("Parsed OK");

                        if (outputAll || wantOutput.Contains(Path.GetFileName(file)))
                        {
                            NTriplesWriter writer = new NTriplesWriter();
                            writer.Save(g, "rdfa_tests\\" + Path.GetFileNameWithoutExtension(file) + ".out");
                        }

                    }
                    catch (IOException ioEx)
                    {
                        reportError(output, "IO Exception", ioEx);
                    }
                    catch (RdfParseException parseEx)
                    {
                        reportError(output, "Parsing Exception", parseEx);
                    }
                    catch (RdfException rdfEx)
                    {
                        reportError(output, "RDF Exception", rdfEx);
                    }
                    catch (Exception ex)
                    {
                        reportError(output, "Other Exception", ex);
                    }
                    finally
                    {
                        timer.Stop();

                        //Write the Triples to the Output
                        foreach (Triple t in g.Triples)
                        {
                            Console.WriteLine(t.ToString());
                        }

                        //Now we run the Test SPARQL (if present)
                        if (File.Exists("rdfa_tests/" + Path.GetFileNameWithoutExtension(file) + ".sparql"))
                        {
                            if (skipCheck.Contains(Path.GetFileName(file)))
                            {
                                output.WriteLine("## Skipping Check of File " + Path.GetFileName(file));
                                output.WriteLine();
                            }
                            else
                            {
                                try
                                {
                                    SparqlQuery q = queryparser.ParseFromFile("rdfa_tests/" + Path.GetFileNameWithoutExtension(file) + ".sparql");
                                    Object results = g.ExecuteQuery(q);
                                    if (results is SparqlResultSet)
                                    {
                                        //The Result is the result of the ASK Query
                                        if (falseTests.Contains(Path.GetFileName(file)))
                                        {
                                            passed = !((SparqlResultSet)results).Result;
                                        }
                                        else
                                        {
                                            passed = ((SparqlResultSet)results).Result;
                                        }
                                    }
                                }
                                catch
                                {
                                    passed = false;
                                }
                            }
                        }

                        if (passed && passDesired)
                        {
                            //Passed and we wanted to Pass
                            testsPassed++;
                            output.WriteLine("# Result = Test Passed");
                            totalTime += timer.ElapsedMilliseconds;
                            totalTriples += g.Triples.Count;
                        }
                        else if (!passed && passDesired)
                        {
                            //Failed when we should have Passed
                            testsFailed++;
                            output.WriteLine("# Result = Test Failed");
                        }
                        else if (passed && !passDesired)
                        {
                            //Passed when we should have Failed
                            testsFailed++;
                            output.WriteLine("# Result = Test Failed");
                        }
                        else
                        {
                            //Failed and we wanted to Fail
                            testsPassed++;
                            output.WriteLine("# Result = Test Passed");
                        }

                        output.WriteLine("# Triples Generated = " + g.Triples.Count());
                        output.WriteLine("# Test Ended at " + DateTime.Now.ToString(TestSuite.TestSuiteTimeFormat));
                    }

                    output.WriteLine();
                }

                output.WriteLine(testsPassed + " Tests Passed");
                output.WriteLine(testsFailed + " Tests Failed");
                output.WriteLine();
                output.Write("Total Parsing Time was " + totalTime + " ms");
                if (totalTime > 1000)
                {
                    output.WriteLine(" (" + totalTime / 1000d + " seconds)");
                }
                output.WriteLine("Average Parsing Speed was " + totalTriples / (totalTime / 1000d) + " triples/second");

            }
            catch (Exception ex)
            {
                reportError(output, "Other Exception", ex);
            }

            Console.SetOut(Console.Out);
            Console.WriteLine("Done");
            Debug.WriteLine("Finished");

            output.Close();

        }
Example #17
0
        public static void TestWriter(StreamWriter output, Graph g, IRdfWriter writer, IRdfReader reader, String file)
        {
            Stopwatch timer = new Stopwatch();

            Console.WriteLine();
            Console.WriteLine(new String('-', file.Length));
            Console.WriteLine(file);
            Console.WriteLine("Attempting serialization with " + writer.GetType().ToString());

            //Show Compression Level
            if (writer is ICompressingWriter)
            {
                Console.WriteLine("Compression Level is " + ((ICompressingWriter)writer).CompressionLevel);
            }

            //Enable Pretty Printing if supported
            if (writer is IPrettyPrintingWriter)
            {
                ((IPrettyPrintingWriter)writer).PrettyPrintMode = true;
            }

            try
            {
                timer.Start();
                writer.Save(g, "writer_tests/" + file + ".out");
                Console.WriteLine("Serialization Done");
            }
            catch (IOException ioEx)
            {
                reportError(output, "IO Exception", ioEx);
            }
            catch (RdfParseException parseEx)
            {
                reportError(output, "Parsing Exception", parseEx);
            }
            catch (RdfException rdfEx)
            {
                reportError(output, "RDF Exception", rdfEx);
            }
            catch (Exception ex)
            {
                reportError(output, "Other Exception", ex);
            }
            finally
            {
                timer.Stop();
                Console.WriteLine("Writing took " + timer.ElapsedMilliseconds + "ms");

                //Get the relevant Reader
                Graph h = new Graph();
                try
                {
                    //Read back in the serialized output to check it's valid RDF
                    Console.WriteLine("Attempting to read back in from serialized Output using " + reader.GetType().ToString());
                    reader.Load(h, "writer_tests/" + file + ".out");
                    Console.WriteLine("Serialized Output was valid RDF");

                    //Check same number of Triples are present
                    if (g.Triples.Count == h.Triples.Count)
                    {
                        Console.WriteLine("Correct number of Triples loaded");
                    }
                    else
                    {
                        throw new RdfException("Incorrect number of Triples loaded, got " + h.Triples.Count + " but expected " + g.Triples.Count);
                    }

                    //Check same number of Subjects are present
                    if (g.Triples.SubjectNodes.Distinct().Count() == h.Triples.SubjectNodes.Distinct().Count())
                    {
                        Console.WriteLine("Correct number of Subjects loaded");
                    }
                    else
                    {
                        throw new RdfException("Incorrect number of Subjects loaded, got " + h.Triples.SubjectNodes.Distinct().Count() + " but expected " + g.Triples.SubjectNodes.Distinct().Count());
                    }

                    //Reserialize to NTriples
                    NTriplesWriter ntwriter = new NTriplesWriter();
                    ntwriter.SortTriples = true;
                    ntwriter.Save(h, "writer_tests/" + file + ".nt");
                    Console.WriteLine("Serialized Output reserialized to NTriples");

                    //Check Graphs are Equal
                    if (g.Equals(h))
                    {
                        Console.WriteLine("Graphs are Equal");
                    }
                    else
                    {
                        Console.WriteLine("First Graphs triples:");
                        foreach (Triple t in g.Triples)
                        {
                            Console.WriteLine(t.ToString());
                        }
                        Console.WriteLine();
                        Console.WriteLine("Second Graph triples:");
                        foreach (Triple t in h.Triples)
                        {
                            Console.WriteLine(t.ToString());
                        }
                        Console.WriteLine();
                        throw new RdfException("Graphs are non-equal");
                    }
                }
                catch (IOException ioEx)
                {
                    reportError(output, "IO Exception", ioEx);
                }
                catch (RdfParseException parseEx)
                {
                    reportError(output, "Parsing Exception", parseEx);
                }
                catch (RdfException rdfEx)
                {
                    reportError(output, "RDF Exception", rdfEx);
                }
                catch (Exception ex)
                {
                    reportError(output, "Other Exception", ex);
                }
                Console.WriteLine();
            }
        }