Beispiel #1
0
        /// <summary>
        /// Compares two Blank Nodes
        /// </summary>
        /// <param name="a">First Blank Node</param>
        /// <param name="b">Second Blank Node</param>
        /// <returns></returns>
        public static int CompareBlankNodes(IBlankNode a, IBlankNode b)
        {
            if (ReferenceEquals(a, b)) return 0;
            if (a == null)
            {
                if (b == null) return 0;
                return -1;
            }
            else if (b == null)
            {
                return 1;
            }

            return a.InternalID.CompareTo(b.InternalID);
        }
Beispiel #2
0
        /// <summary>
        /// Determines whether two Blank Nodes are equal
        /// </summary>
        /// <param name="a">First Blank Node</param>
        /// <param name="b">Second Blank Node</param>
        /// <returns></returns>
        public static bool AreBlankNodesEqual(IBlankNode a, IBlankNode b)
        {
            if (ReferenceEquals(a, b)) return true;
            if (a == null)
            {
                if (b == null) return true;
                return false;
            }
            else if (b == null)
            {
                return false;
            }

            return a.InternalID.Equals(b.InternalID) && ReferenceEquals(a.Graph, b.Graph);
        }
        /// <summary>
        /// Method which generates the RDF Graph of a SPARQL Result Set.
        /// </summary>
        /// <param name="results">Result Set.</param>
        /// <returns></returns>
        public IGraph GenerateOutput(SparqlResultSet results)
        {
            // Create the Graph for the Output
            IGraph g = new Graph();

            // Add the relevant namespaces
            g.NamespaceMap.AddNamespace("rs", UriFactory.Create(SparqlSpecsHelper.SparqlRdfResultsNamespace));

            // Create relevant Nodes
            IUriNode rdfType        = g.CreateUriNode("rdf:type");
            IUriNode resultSetClass = g.CreateUriNode("rs:ResultSet");
            IUriNode resultVariable = g.CreateUriNode("rs:resultVariable");
            IUriNode solution       = g.CreateUriNode("rs:solution");
            IUriNode binding        = g.CreateUriNode("rs:binding");
            IUriNode value          = g.CreateUriNode("rs:value");
            IUriNode variable       = g.CreateUriNode("rs:variable");
            IUriNode boolean        = g.CreateUriNode("rs:boolean");

            // First we declare a Result Set
            IBlankNode rset = g.CreateBlankNode();

            g.Assert(new Triple(rset, rdfType, resultSetClass));

            if (results.ResultsType == SparqlResultsType.VariableBindings)
            {
                // Assert a Triple for each Result Variable
                foreach (String v in results.Variables)
                {
                    g.Assert(new Triple(rset, resultVariable, g.CreateLiteralNode(v)));
                }

                // Then we're going to define a solution for each result
                foreach (SparqlResult r in results)
                {
                    IBlankNode sln = g.CreateBlankNode();
                    g.Assert(new Triple(rset, solution, sln));

                    foreach (String v in results.Variables)
                    {
                        // Only define Bindings if there is a value and it is non-null
                        if (r.HasValue(v) && r[v] != null)
                        {
                            IBlankNode bnd = g.CreateBlankNode();
                            g.Assert(new Triple(sln, binding, bnd));
                            g.Assert(new Triple(bnd, variable, g.CreateLiteralNode(v)));
                            switch (r[v].NodeType)
                            {
                            case NodeType.Blank:
                                IBlankNode b = (IBlankNode)r[v];
                                IBlankNode bMapped;
                                if (b.GraphUri == null)
                                {
                                    bMapped = g.CreateBlankNode(b.InternalID + "def");
                                }
                                else
                                {
                                    bMapped = g.CreateBlankNode(b.InternalID + b.GraphUri.GetEnhancedHashCode());
                                }
                                g.Assert(new Triple(bnd, value, bMapped));
                                break;

                            case NodeType.GraphLiteral:
                                throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("SPARQL Results RDF Serialization"));

                            case NodeType.Literal:
                            case NodeType.Uri:
                                g.Assert(new Triple(bnd, value, r[v].CopyNode(g)));
                                break;

                            default:
                                throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("SPARQL Results RDF Serialization"));
                            }
                        }
                    }
                }
            }
            else
            {
                // A Boolean Result Set
                g.Assert(new Triple(rset, boolean, g.CreateLiteralNode(results.Result.ToString(), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeBoolean))));
            }

            return(g);
        }
 public int CompareTo(IBlankNode other)
 {
     return(_source.CompareTo(other));
 }
Beispiel #5
0
 /// <summary>
 /// Nodes must implement a CompareTo method to allow them to be Sorted
 /// </summary>
 /// <param name="other">Node to compare self to</param>
 /// <returns></returns>
 /// <remarks>
 /// Implementations should use the SPARQL Term Sort Order for ordering nodes (as opposed to value sort order).  Standard implementations of Node type specific comparisons can be found in <see cref="ComparisonHelper">ComparisonHelper</see>
 /// </remarks>
 public abstract int CompareTo(IBlankNode other);
Beispiel #6
0
        /// <summary>
        /// Takes a <see cref="INode">INode</see> and converts it to a <see cref="IValuedNode">IValuedNode</see> if it is not already an instance that implements the interface.
        /// </summary>
        /// <param name="n">Node.</param>
        /// <returns>Valued Node.</returns>
        public static IValuedNode AsValuedNode(this INode n)
        {
            if (n == null)
            {
                return(null);
            }
            if (n is IValuedNode)
            {
                return((IValuedNode)n);
            }

            switch (n.NodeType)
            {
            case NodeType.Blank:
                IBlankNode b = (IBlankNode)n;
                return(new BlankNode(n.Graph, b.InternalID));

            case NodeType.GraphLiteral:
                IGraphLiteralNode glit = (IGraphLiteralNode)n;
                return(new GraphLiteralNode(n.Graph, glit.SubGraph));

            case NodeType.Literal:
                ILiteralNode lit = (ILiteralNode)n;
                // Decide what kind of valued node to produce based on node datatype
                if (lit.DataType != null)
                {
                    String dt = lit.DataType.AbsoluteUri;
                    switch (dt)
                    {
                    case XmlSpecsHelper.XmlSchemaDataTypeBoolean:
                        bool bVal;
                        if (Boolean.TryParse(lit.Value, out bVal))
                        {
                            return(new BooleanNode(n.Graph, bVal));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeByte:
                        // xsd:byte actually maps to SignedByte in .Net
                        sbyte sbVal;
                        if (sbyte.TryParse(lit.Value, out sbVal))
                        {
                            return(new SignedByteNode(n.Graph, sbVal, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeDate:
                        DateTime date;
                        if (DateTime.TryParse(lit.Value, null, DateTimeStyles.AdjustToUniversal, out date))
                        {
                            return(new DateNode(n.Graph, date, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeDateTime:
                        DateTime dateTime;
                        if (DateTime.TryParse(lit.Value, null, DateTimeStyles.AdjustToUniversal, out dateTime))
                        {
                            return(new DateTimeNode(n.Graph, dateTime, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeDayTimeDuration:
                    case XmlSpecsHelper.XmlSchemaDataTypeDuration:
                        TimeSpan timeSpan;
                        try
                        {
                            timeSpan = XmlConvert.ToTimeSpan(lit.Value);
                            return(new TimeSpanNode(n.Graph, timeSpan, lit.Value, lit.DataType));
                        }
                        catch
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeDecimal:
                        Decimal dec;
                        if (Decimal.TryParse(lit.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out dec))
                        {
                            return(new DecimalNode(n.Graph, dec, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeDouble:
                        Double dbl;
                        if (Double.TryParse(lit.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out dbl))
                        {
                            return(new DoubleNode(n.Graph, dbl, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeFloat:
                        Single flt;
                        if (Single.TryParse(lit.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out flt))
                        {
                            return(new FloatNode(n.Graph, flt, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeInt:
                    case XmlSpecsHelper.XmlSchemaDataTypeInteger:
                    case XmlSpecsHelper.XmlSchemaDataTypeLong:
                    case XmlSpecsHelper.XmlSchemaDataTypeShort:
                        long lng;
                        if (Int64.TryParse(lit.Value, out lng))
                        {
                            return(new LongNode(n.Graph, lng, lit.Value, lit.DataType));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeNegativeInteger:
                    case XmlSpecsHelper.XmlSchemaDataTypeNonPositiveInteger:
                        // Must be below zero
                        long neglng;
                        if (Int64.TryParse(lit.Value, out neglng) && neglng < 0)
                        {
                            return(new LongNode(n.Graph, neglng, lit.Value, lit.DataType));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeNonNegativeInteger:
                    case XmlSpecsHelper.XmlSchemaDataTypePositiveInteger:
                        // Must be above zero
                        long poslng;
                        if (Int64.TryParse(lit.Value, out poslng) && poslng >= 0)
                        {
                            return(new LongNode(n.Graph, poslng, lit.Value, lit.DataType));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeUnsignedByte:
                        // xsd:unsignedByte actually maps to Byte in .Net
                        byte byVal;
                        if (byte.TryParse(lit.Value, out byVal))
                        {
                            return(new ByteNode(n.Graph, byVal, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeUnsignedInt:
                    case XmlSpecsHelper.XmlSchemaDataTypeUnsignedLong:
                    case XmlSpecsHelper.XmlSchemaDataTypeUnsignedShort:
                        // Must be unsigned
                        ulong ulng;
                        if (UInt64.TryParse(lit.Value, out ulng))
                        {
                            return(new UnsignedLongNode(n.Graph, ulng, lit.Value, lit.DataType));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    default:
                        if (SparqlSpecsHelper.IntegerDataTypes.Contains(dt))
                        {
                            long l;
                            if (Int64.TryParse(lit.Value, out l))
                            {
                                return(new LongNode(n.Graph, l, lit.Value, lit.DataType));
                            }
                            else
                            {
                                return(new StringNode(n.Graph, lit.Value, lit.DataType));
                            }
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }
                    }
                }
                else if (!lit.Language.Equals(String.Empty))
                {
                    return(new StringNode(n.Graph, lit.Value, lit.Language));
                }
                else
                {
                    return(new StringNode(n.Graph, lit.Value));
                }

            case NodeType.Uri:
                IUriNode u = (IUriNode)n;
                return(new UriNode(n.Graph, u.Uri));

            case NodeType.Variable:
                IVariableNode v = (IVariableNode)n;
                return(new VariableNode(n.Graph, v.VariableName));

            default:
                throw new RdfQueryException("Cannot create a valued node for an unknown node type");
            }
        }
Beispiel #7
0
 /// <summary>
 /// Determines whether this Node is equal to another
 /// </summary>
 /// <param name="other">Other Blank Node</param>
 /// <returns></returns>
 public override bool Equals(IBlankNode other)
 {
     return(EqualityHelper.AreBlankNodesEqual(this, other));
 }
Beispiel #8
0
        public void StorageVirtuosoBlankNodePersistence()
        {
            //Create our Test Graph
            Graph g = new Graph();

            g.BaseUri = new Uri("http://example.org/bnodes/");
            g.NamespaceMap.AddNamespace(String.Empty, g.BaseUri);

            IBlankNode b       = g.CreateBlankNode("blank");
            IUriNode   rdfType = g.CreateUriNode("rdf:type");
            IUriNode   bnode   = g.CreateUriNode(":BlankNode");

            g.Assert(new Triple(b, rdfType, bnode));

            Assert.Equal(1, g.Triples.Count);

            //Connect to Virtuoso
            VirtuosoManager manager = VirtuosoTest.GetConnection();

            try
            {
                //Save Graph
                manager.SaveGraph(g);

                //Retrieve
                Graph h = new Graph();
                Graph i = new Graph();
                manager.LoadGraph(h, g.BaseUri);
                manager.LoadGraph(i, g.BaseUri);

                Assert.Equal(1, h.Triples.Count);
                Assert.Equal(1, i.Triples.Count);

                Console.WriteLine("Contents of Retrieved Graph:");
                foreach (Triple t in h.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
                Console.WriteLine();

                TestTools.CompareGraphs(h, i, true);

                //Save back again
                manager.SaveGraph(h);

                //Retrieve again
                Graph j = new Graph();
                manager.LoadGraph(j, g.BaseUri);

                Console.WriteLine("Contents of Retrieved Graph (Retrieved after saving original Retrieval):");
                foreach (Triple t in j.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
                Console.WriteLine();

                TestTools.CompareGraphs(h, j, false);
                TestTools.CompareGraphs(i, j, false);

                //Save back yet again
                manager.SaveGraph(j);

                //Retrieve yet again
                Graph k = new Graph();
                manager.LoadGraph(k, g.BaseUri);

                Console.WriteLine("Contents of Retrieved Graph (Retrieved after saving second Retrieval):");
                foreach (Triple t in k.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
                Console.WriteLine();

                TestTools.CompareGraphs(j, k, false);
            }
            finally
            {
                if (manager != null)
                {
                    manager.Dispose();
                }
            }
        }
        public void WritingFormattingTriples()
        {
            try
            {
                //Create the Graph and define an additional namespace
                Graph g = new Graph();
                g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));

                //Create URIs used for datatypes
                Uri dtInt        = new Uri(XmlSpecsHelper.XmlSchemaDataTypeInteger);
                Uri dtFloat      = new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat);
                Uri dtDouble     = new Uri(XmlSpecsHelper.XmlSchemaDataTypeDouble);
                Uri dtDecimal    = new Uri(XmlSpecsHelper.XmlSchemaDataTypeDecimal);
                Uri dtBoolean    = new Uri(XmlSpecsHelper.XmlSchemaDataTypeBoolean);
                Uri dtUnknown    = new Uri("http://example.org/unknownType");
                Uri dtXmlLiteral = new Uri(RdfSpecsHelper.RdfXmlLiteral);

                //Create Nodes used for our test Triples
                IBlankNode   subjBnode     = g.CreateBlankNode();
                IUriNode     subjUri       = g.CreateUriNode(new Uri("http://example.org/subject"));
                IUriNode     subjUri2      = g.CreateUriNode(new Uri("http://example.org/123"));
                IUriNode     predUri       = g.CreateUriNode(new Uri("http://example.org/vocab#predicate"));
                IUriNode     predType      = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
                IBlankNode   objBnode      = g.CreateBlankNode();
                IUriNode     objUri        = g.CreateUriNode(new Uri("http://example.org/object"));
                ILiteralNode objString     = g.CreateLiteralNode("This is a literal");
                ILiteralNode objStringLang = g.CreateLiteralNode("This is a literal with a language specifier", "en");
                ILiteralNode objInt        = g.CreateLiteralNode("123", dtInt);
                ILiteralNode objFloat      = g.CreateLiteralNode("12.3e4", dtFloat);
                ILiteralNode objDouble     = g.CreateLiteralNode("12.3e4", dtDouble);
                ILiteralNode objDecimal    = g.CreateLiteralNode("12.3", dtDecimal);
                ILiteralNode objTrue       = g.CreateLiteralNode("true", dtBoolean);
                ILiteralNode objFalse      = g.CreateLiteralNode("false", dtBoolean);
                ILiteralNode objUnknown    = g.CreateLiteralNode("This is a literal with an unknown type", dtUnknown);
                ILiteralNode objXmlLiteral = g.CreateLiteralNode("<strong>XML Literal</strong>", dtXmlLiteral);

                List <ITripleFormatter> formatters = new List <ITripleFormatter>()
                {
                    new NTriplesFormatter(),
                    new UncompressedTurtleFormatter(),
                    new UncompressedNotation3Formatter(),
                    new TurtleFormatter(g),
                    new TurtleW3CFormatter(g),
                    new Notation3Formatter(g),
                    new CsvFormatter(),
                    new TsvFormatter(),
                    new RdfXmlFormatter()
                };
                List <INode> subjects = new List <INode>()
                {
                    subjBnode,
                    subjUri,
                    subjUri2
                };
                List <INode> predicates = new List <INode>()
                {
                    predUri,
                    predType
                };
                List <INode> objects = new List <INode>()
                {
                    objBnode,
                    objUri,
                    objString,
                    objStringLang,
                    objInt,
                    objFloat,
                    objDouble,
                    objDecimal,
                    objTrue,
                    objFalse,
                    objUnknown,
                    objXmlLiteral
                };
                List <Triple> testTriples = new List <Triple>();
                foreach (INode s in subjects)
                {
                    foreach (INode p in predicates)
                    {
                        foreach (INode o in objects)
                        {
                            testTriples.Add(new Triple(s, p, o));
                        }
                    }
                }

                foreach (Triple t in testTriples)
                {
                    Console.WriteLine("Raw Triple:");
                    Console.WriteLine(t.ToString());
                    Console.WriteLine();
                    foreach (ITripleFormatter f in formatters)
                    {
                        Console.WriteLine(f.GetType().ToString());
                        Console.WriteLine(f.Format(t));
                        Console.WriteLine();
                    }
                    Console.WriteLine();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
 /// <summary>
 /// Given a Blank Node returns a Graph scoped Node ID
 /// </summary>
 /// <param name="value">Blank Node</param>
 /// <returns></returns>
 /// <remarks>
 /// Should function as equivalent to the two argument version with the <strong>createIfNotExists</strong> parameter set to false
 /// </remarks>
 public ulong GetBlankNodeID(IBlankNode value)
 {
     return(GetBlankNodeID(value, false));
 }
Beispiel #11
0
        private void TestBNodeFormatting(IBlankNode b, INodeFormatter formatter, String expected)
        {
            String actual = formatter.Format(b);

            Assert.AreEqual(expected, actual);
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            IGraph g = new Graph();

            IUriNode     dotNetRDF    = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org"));
            IUriNode     says         = g.CreateUriNode(UriFactory.Create("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));



            Notation3Parser n3parser = new Notation3Parser();

            try
            {
                //Load using Filename
                n3parser.Load(g, "szepmuveszeti.n3");
            }
            catch (RdfParseException parseEx)
            {
                //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc.
                Console.WriteLine("Parser Error");
                Console.WriteLine(parseEx.Message);
            }
            catch (RdfException rdfEx)
            {
                //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace
                Console.WriteLine("RDF Error");
                Console.WriteLine(rdfEx.Message);
            }

            IBlankNode b = g.GetBlankNode("nodeID");

            if (b != null)
            {
                Console.WriteLine("Blank Node with ID " + b.InternalID + " exists in the Graph");
            }
            else
            {
                Console.WriteLine("No Blank Node with the given ID existed in the Graph");
            }



            int i = 0;

            foreach (Triple t in g.Triples)
            {
                Console.WriteLine(t.ToString());
                i++;
                if (i == 100)
                {
                    break;
                }
            }

            Console.ReadKey();
        }
        private static IUriNode FindOwningSubject(this TripleStore store, IBlankNode blankNode)
        {
            INode result = blankNode;
            do
            {
                Triple triple = store.Triples.Where(item => item.Object.Equals(result)).FirstOrDefault();
                if (triple != null)
                {
                    result = triple.Subject;
                }
                else
                {
                    result = null;
                }
            }
            while ((result != null) && (result is IBlankNode));

            return (IUriNode)result;
        }
Beispiel #14
0
 public FluentGraphPredicateBuilder AndAnonymousObject(out IBlankNode bnode)
 {
     bnode = _graph.CreateBlankNode();
     _objectNodes.Add(bnode);
     return(this);
 }
Beispiel #15
0
        public void CoreDataModel()
        {
            // 1. A Graph--------------------------------------------------------------------
            // We start off by needing a container for our triples so we create a new Graph.
            IGraph g = new Graph {
                BaseUri = new Uri("http://www.example.org/")
            };
            // ------------------------------------------------------------------------------

            // 2. URI Nodes -----------------------------------------------------------------
            // Triples are composed of INode things so we create some of these aswell.
            // Create a URI Node that refers to some specific URI
            IUriNode dotNetRDF = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org"));

            //Create a URI Node using a QName but we need to define a Namespace first
            g.NamespaceMap.AddNamespace("ex", UriFactory.Create("http://example.org/namespace/"));
            IUriNode demo = g.CreateUriNode("ex:demo");

            // we use the Create() method of the UriFactory class to create URIs since this takes advantage of dotNetRDF's
            // URI interning feature to reduce memory usage and speed up equality comparisons on URIs.
            // ------------------------------------------------------------------------------

            // 3. Blank Nodes ---------------------------------------------------------------
            // As well as URI nodes triples can also contain Blank nodes. A Blank node represents
            // an anonymous resource.

            // Create an anonymous Blank Node
            // Each call to this constructor generates a Blank Node with a new unique identifier within the Graph
            IBlankNode anon = g.CreateBlankNode();

            // Create a named Blank Node
            // Reusing the same ID results in the same Blank Node within the Graph
            // Note that if the ID refers to an automatically assigned ID that is already in use the returned
            // Blank Node will be given an alternative ID
            IBlankNode named = g.CreateBlankNode("ID");

            // name clash with auto assigned ID
            IBlankNode namedAgain = g.CreateBlankNode(anon.InternalID);

            Assert.AreEqual("ID", named.InternalID);
            Assert.AreNotEqual(anon.InternalID, namedAgain.InternalID);

            // ------------------------------------------------------------------------------

            // 4. Literal Nodes -------------------------------------------------------------
            // Literal nodes consist of a value, a datatype and a language code. The second two
            // are optional.

            // Create a Plain Literal
            ILiteralNode plain = g.CreateLiteralNode("some value");

            Assert.IsNull(plain.DataType);
            Assert.IsTrue(string.IsNullOrEmpty(plain.Language));
            Assert.AreEqual("some value", plain.Value);

            // Create some Language Specified Literal
            ILiteralNode hello   = g.CreateLiteralNode("hello", "en");
            ILiteralNode bonjour = g.CreateLiteralNode("bonjour", "fr");

            // Create some typed Literals
            ILiteralNode number = g.CreateLiteralNode("1", UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeInteger));
            ILiteralNode tr     = g.CreateLiteralNode("true", UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeBoolean));

            // Literal Node equality is somewhat more complex but basically follows the following rules:
            //    If a Language Specifier is present both Nodes must have an identical Language Specifier
            //    If a Data Type URI is present both Nodes must have an identical Data Type URI
            //    The String value of the Literal must match on a character by character basis (using Ordinal comparison)

            ILiteralNode one1 = g.CreateLiteralNode("1", UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeInteger));
            ILiteralNode one2 = g.CreateLiteralNode("0001", UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeInteger));

            // Use Options.LiteralEqualityMode = LiteralEqualityMode.Loose; to perform equality based on typed values
            // rather than the string representation. This is a global flag and has overhead so should be used sparingly.

            Assert.IsFalse(one1.Equals(one2));
            Options.LiteralEqualityMode = LiteralEqualityMode.Loose;
            Assert.IsTrue(one1.Equals(one2));
            // ------------------------------------------------------------------------------

            // 5. Triple --------------------------------------------------------------------
            g = new Graph();

            // Create some Nodes
            dotNetRDF = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org"));
            IUriNode     createdBy = g.CreateUriNode(UriFactory.Create("http://example.org/createdBy"));
            ILiteralNode robVesse  = g.CreateLiteralNode("Rob Vesse");

            // Assert this Triple
            Triple t = new Triple(dotNetRDF, createdBy, robVesse);

            g.Assert(t);
            Assert.AreEqual(1, g.Triples.Count);
            // ------------------------------------------------------------------------------
        }
 private static void AddBlankNodeFilter(this IGraphPatternBuilder builder, IBlankNode n)
 {
     builder.Filter(node =>
                    node.IsBlank(n.InternalID));
 }
Beispiel #17
0
 /// <summary>
 /// Creates a new Virtual Blank Node
 /// </summary>
 /// <param name="g">Graph the Node belongs to</param>
 /// <param name="id">Virtual ID</param>
 /// <param name="provider">Virtual RDF Provider</param>
 /// <param name="value">Materialised Value</param>
 public SimpleVirtualBlankNode(IGraph g, int id, IVirtualRdfProvider <int, int> provider, IBlankNode value)
     : base(g, id, provider, value)
 {
 }
Beispiel #18
0
 /// <summary>
 /// Formats a Blank Node as a String for the given Format
 /// </summary>
 /// <param name="b">Blank Node</param>
 /// <param name="segment">Triple Segment</param>
 /// <returns></returns>
 protected virtual String FormatBlankNode(IBlankNode b, TripleSegment? segment)
 {
     if (segment == TripleSegment.Predicate) throw new RdfOutputException(WriterErrorMessages.BlankPredicatesUnserializable(this._format));
     return b.ToString();
 }
Beispiel #19
0
 protected override string FormatBlankNode(IBlankNode b, TripleSegment?segment)
 {
     return("_:" + b.InternalID);
 }
Beispiel #20
0
        /// <summary>
        /// Merges another Graph into the current Graph
        /// </summary>
        /// <param name="g">Graph to Merge into this Graph</param>
        /// <param name="keepOriginalGraphUri">Indicates that the Merge should preserve the Graph URIs of Nodes so they refer to the Graph they originated in</param>
        /// <remarks>
        /// <para>
        /// The Graph on which you invoke this method will preserve its Blank Node IDs while the Blank Nodes from the Graph being merged in will be given new IDs as required in the scope of this Graph.
        /// </para>
        /// <para>
        /// The Graph will raise the <see cref="MergeRequested">MergeRequested</see> event before the Merge operation which gives any event handlers the oppurtunity to cancel this event.  When the Merge operation is completed the <see cref="Merged">Merged</see> event is raised
        /// </para>
        /// </remarks>
        public virtual void Merge(IGraph g, bool keepOriginalGraphUri)
        {
            if (ReferenceEquals(this, g))
            {
                throw new RdfException("You cannot Merge an RDF Graph with itself");
            }

            // Check that the merge can go ahead
            if (!RaiseMergeRequested())
            {
                return;
            }

            // First copy and Prefixes across which aren't defined in this Graph
            _nsmapper.Import(g.NamespaceMap);

            if (IsEmpty)
            {
                // Empty Graph so do a quick copy
                foreach (Triple t in g.Triples)
                {
                    Assert(new Triple(Tools.CopyNode(t.Subject, this, keepOriginalGraphUri), Tools.CopyNode(t.Predicate, this, keepOriginalGraphUri), Tools.CopyNode(t.Object, this, keepOriginalGraphUri), t.Context));
                }
            }
            else
            {
                // Prepare a mapping of Blank Nodes to Blank Nodes
                Dictionary <INode, IBlankNode> mapping = new Dictionary <INode, IBlankNode>();

                foreach (Triple t in g.Triples)
                {
                    INode s, p, o;
                    if (t.Subject.NodeType == NodeType.Blank)
                    {
                        if (!mapping.ContainsKey(t.Subject))
                        {
                            IBlankNode temp = CreateBlankNode();
                            if (keepOriginalGraphUri)
                            {
                                temp.GraphUri = t.Subject.GraphUri;
                            }
                            mapping.Add(t.Subject, temp);
                        }
                        s = mapping[t.Subject];
                    }
                    else
                    {
                        s = Tools.CopyNode(t.Subject, this, keepOriginalGraphUri);
                    }

                    if (t.Predicate.NodeType == NodeType.Blank)
                    {
                        if (!mapping.ContainsKey(t.Predicate))
                        {
                            IBlankNode temp = CreateBlankNode();
                            if (keepOriginalGraphUri)
                            {
                                temp.GraphUri = t.Predicate.GraphUri;
                            }
                            mapping.Add(t.Predicate, temp);
                        }
                        p = mapping[t.Predicate];
                    }
                    else
                    {
                        p = Tools.CopyNode(t.Predicate, this, keepOriginalGraphUri);
                    }

                    if (t.Object.NodeType == NodeType.Blank)
                    {
                        if (!mapping.ContainsKey(t.Object))
                        {
                            IBlankNode temp = CreateBlankNode();
                            if (keepOriginalGraphUri)
                            {
                                temp.GraphUri = t.Object.GraphUri;
                            }
                            mapping.Add(t.Object, temp);
                        }
                        o = mapping[t.Object];
                    }
                    else
                    {
                        o = Tools.CopyNode(t.Object, this, keepOriginalGraphUri);
                    }

                    Assert(new Triple(s, p, o, t.Context));
                }
            }

            RaiseMerged();
        }
Beispiel #21
0
        /// <summary>
        /// Takes lists of Triples added and removed and generates a ChangeSet Batch Graph for these
        /// </summary>
        /// <param name="additions">Triple added</param>
        /// <param name="removals">Triples removed</param>
        /// <returns>Null if there are no Changes to be persisted</returns>
        private IGraph GenerateChangeSet(IEnumerable <Triple> additions, IEnumerable <Triple> removals)
        {
            //Ensure there are no duplicates in the lists
            List <Triple> toAdd    = (additions == null) ? new List <Triple>() : additions.Distinct().ToList();
            List <Triple> toRemove = (removals == null) ? new List <Triple>() : removals.Distinct().ToList();

            //Eliminate any additions that have also been retracted
            List <Triple> temp = new List <Triple>();

            foreach (Triple t in toAdd)
            {
                if (toRemove.Contains(t))
                {
                    temp.Add(t);
                }
            }
            //If it was in both lists we don't need to persist the Change as it has effectively not happened
            toAdd.RemoveAll(t => temp.Contains(t));
            toRemove.RemoveAll(t => temp.Contains(t));

            //Nothing to do if both lists are now empty
            if (toAdd.Count == 0 && toRemove.Count == 0)
            {
                return(null);
            }

            //Now we need to build a ChangeSet Graph
            Graph g = new Graph();

            g.BaseUri = UriFactory.Create("http://www.dotnetrdf.org/");
            g.NamespaceMap.AddNamespace("cs", UriFactory.Create(TalisChangeSetNamespace));

            //Make all the Nodes we need
            IUriNode     rdfType            = g.CreateUriNode("rdf:type");
            IUriNode     changeSet          = g.CreateUriNode("cs:ChangeSet");
            IUriNode     subjOfChange       = g.CreateUriNode("cs:subjectOfChange");
            IUriNode     createdDate        = g.CreateUriNode("cs:createdDate");
            ILiteralNode now                = g.CreateLiteralNode(DateTime.Now.ToString(XmlSpecsHelper.XmlSchemaDateTimeFormat));
            IUriNode     creator            = g.CreateUriNode("cs:creatorName");
            ILiteralNode dotNetRDF          = g.CreateLiteralNode("dotNetRDF");
            IUriNode     changeReason       = g.CreateUriNode("cs:changeReason");
            ILiteralNode dotNetRDFUpdate    = g.CreateLiteralNode("Updates to the store were requested by a dotNetRDF powered application");
            IUriNode     precedingChangeset = g.CreateUriNode("cs:precedingChangeSet");
            IUriNode     removal            = g.CreateUriNode("cs:removal");
            IUriNode     addition           = g.CreateUriNode("cs:addition");
            IUriNode     rdfStmt            = g.CreateUriNode("rdf:Statement");
            IUriNode     rdfSubj            = g.CreateUriNode("rdf:subject");
            IUriNode     rdfPred            = g.CreateUriNode("rdf:predicate");
            IUriNode     rdfObj             = g.CreateUriNode("rdf:object");

            //Find the Distinct Subjects from the list
            IEnumerable <INode> subjects = (from t in toAdd select t.Subject).Concat(from t in toRemove select t.Subject).Distinct();

            foreach (INode subj in subjects)
            {
                //Create a ChangeSet for this Subject
                IUriNode report = g.CreateUriNode(UriFactory.Create(Tools.ResolveUri(subj.GetHashCode() + "/changes/" + DateTime.Now.ToString(TalisChangeSetIDFormat), g.BaseUri.ToString())));
                g.Assert(new Triple(report, rdfType, changeSet));
                g.Assert(new Triple(report, subjOfChange, Tools.CopyNode(subj, g)));
                g.Assert(new Triple(report, createdDate, now));
                g.Assert(new Triple(report, creator, dotNetRDF));
                g.Assert(new Triple(report, changeReason, dotNetRDFUpdate));

                //Add Additions to this ChangeSet
                foreach (Triple t in toAdd.Where(t2 => t2.Subject.Equals(subj)))
                {
                    IBlankNode b = g.CreateBlankNode();
                    g.Assert(new Triple(report, addition, b));
                    g.Assert(new Triple(b, rdfType, rdfStmt));
                    g.Assert(new Triple(b, rdfSubj, Tools.CopyNode(t.Subject, g)));
                    g.Assert(new Triple(b, rdfPred, Tools.CopyNode(t.Predicate, g)));
                    g.Assert(new Triple(b, rdfObj, Tools.CopyNode(t.Object, g)));
                }

                //Add Removals to this ChangeSet
                foreach (Triple t in toRemove.Where(t2 => t2.Subject.Equals(subj)))
                {
                    IBlankNode b = g.CreateBlankNode();
                    g.Assert(new Triple(report, removal, b));
                    g.Assert(new Triple(b, rdfType, rdfStmt));
                    g.Assert(new Triple(b, rdfSubj, Tools.CopyNode(t.Subject, g)));
                    g.Assert(new Triple(b, rdfPred, Tools.CopyNode(t.Predicate, g)));
                    g.Assert(new Triple(b, rdfObj, Tools.CopyNode(t.Object, g)));
                }
            }

            return(g);
        }
        /// <summary>
        /// Internal Helper Method for converting Blank Nodes to DOT notation
        /// </summary>
        /// <param name="b">Blank Node to Convert</param>
        /// <returns></returns>
        private String BlankNodeToDot(IBlankNode b)
        {
            //Generate a _: QName
            StringBuilder output = new StringBuilder();
            output.Append("\"_:");
            output.Append(b.InternalID);
            output.Append("\"");

            return output.ToString();
        }
Beispiel #23
0
        /// <summary>
        /// Copies a Node so it can be used in another Graph since by default Triples cannot contain Nodes from more than one Graph
        /// </summary>
        /// <param name="original">Node to Copy</param>
        /// <param name="target">Graph to Copy into</param>
        /// <returns></returns>
        /// <remarks>
        /// <para>
        /// <strong>Warning:</strong> Copying Blank Nodes may lead to unforseen circumstances since no remapping of IDs between Graphs is done
        /// </para>
        /// </remarks>
        public static INode CopyNode(INode original, IGraph target)
        {
            // No need to copy if it's already in the relevant Graph
            if (ReferenceEquals(original.Graph, target))
            {
                return(original);
            }

            // if a node can copy itself then let it do it
            var selfcopyable_original = original as RDF.Storage.Virtualisation.ICanCopy;

            if (selfcopyable_original != null)
            {
                return(selfcopyable_original.CopyNode(target));
            }

            // if it doesn't, copy it's values:

            if (original.NodeType == NodeType.Uri)
            {
                IUriNode u  = (IUriNode)original;
                IUriNode u2 = new UriNode(target, u.Uri);

                return(u2);
            }
            else if (original.NodeType == NodeType.Literal)
            {
                ILiteralNode l = (ILiteralNode)original;
                ILiteralNode l2;
                if (l.Language.Equals(String.Empty))
                {
                    if (!(l.DataType == null))
                    {
                        l2 = new LiteralNode(target, l.Value, l.DataType);
                    }
                    else
                    {
                        l2 = new LiteralNode(target, l.Value);
                    }
                }
                else
                {
                    l2 = new LiteralNode(target, l.Value, l.Language);
                }

                return(l2);
            }
            else if (original.NodeType == NodeType.Blank)
            {
                IBlankNode b = (IBlankNode)original;
                IBlankNode b2;

                b2 = new BlankNode(target, b.InternalID);
                return(b2);
            }
            else if (original.NodeType == NodeType.Variable)
            {
                IVariableNode v = (IVariableNode)original;
                return(new VariableNode(target, v.VariableName));
            }
            else
            {
                throw new RdfException("Unable to Copy '" + original.GetType().ToString() + "' Nodes between Graphs");
            }
        }
Beispiel #24
0
        public void NodeCompareToMixedNodes3()
        {
            Graph g = new Graph();
            Graph h = new Graph();

            IBlankNode   b     = g.CreateBlankNode();
            ILiteralNode plain = g.CreateLiteralNode("plain");
            IUriNode     u     = g.CreateUriNode("rdf:type");
            List <INode> nodes = new List <INode>()
            {
                b,
                g.CreateBlankNode(),
                g.CreateBlankNode("id"),
                g.CreateLiteralNode("1.2e3", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                g.CreateLiteralNode("1.2", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                g.CreateLiteralNode("1.2e1", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                g.CreateLiteralNode("10", new Uri(XmlSpecsHelper.XmlSchemaDataTypeShort)),
                g.CreateLiteralNode("-3", new Uri(XmlSpecsHelper.XmlSchemaDataTypeShort)),
                g.CreateLiteralNode("1.2E4", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                g.CreateLiteralNode("http://example.org:8080", new Uri(XmlSpecsHelper.XmlSchemaDataTypeAnyUri)),
                g.CreateLiteralNode("http://example.org/path", new Uri(XmlSpecsHelper.XmlSchemaDataTypeAnyUri)),
                g.CreateLiteralNode("ftp://ftp.example.org", new Uri(XmlSpecsHelper.XmlSchemaDataTypeAnyUri)),
                g.CreateLiteralNode("1.2e0", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                DateTime.Now.ToLiteral(g),
                DateTime.Now.AddYears(3).AddDays(1).ToLiteral(g),
                DateTime.Now.AddYears(-25).AddMinutes(-17).ToLiteral(g),
                g.CreateLiteralNode("1.2e-1", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                g.CreateLiteralNode("10", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                g.CreateLiteralNode("10e14", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                h.CreateBlankNode(),
                h.CreateBlankNode("id"),
                b,
                plain,
                g.CreateLiteralNode("plain english", "en"),
                g.CreateLiteralNode("1", new Uri(XmlSpecsHelper.XmlSchemaDataTypeInteger)),
                g.CreateLiteralNode("10", new Uri(XmlSpecsHelper.XmlSchemaDataTypeInteger)),
                g.CreateLiteralNode("plain french", "fr"),
                g.CreateLiteralNode("typed", new Uri(XmlSpecsHelper.XmlSchemaDataTypeString)),
                (1234).ToLiteral(g),
                (12.34m).ToLiteral(g),
                (12.34d).ToLiteral(g),
                (false).ToLiteral(g),
                g.CreateLiteralNode((1).ToString("X2"), new Uri(XmlSpecsHelper.XmlSchemaDataTypeHexBinary)),
                g.CreateLiteralNode((10).ToString("X2"), new Uri(XmlSpecsHelper.XmlSchemaDataTypeHexBinary)),
                (true).ToLiteral(g),
                plain,
                u,
                g.CreateUriNode(new Uri("http://example.org")),
                g.CreateUriNode(new Uri("http://example.org:8080")),
                g.CreateLiteralNode("1", new Uri(XmlSpecsHelper.XmlSchemaDataTypeByte)),
                g.CreateLiteralNode("10", new Uri(XmlSpecsHelper.XmlSchemaDataTypeByte)),
                g.CreateLiteralNode("-3", new Uri(XmlSpecsHelper.XmlSchemaDataTypeByte)),
                g.CreateUriNode(new Uri("http://www.dotnetrdf.org")),
                g.CreateUriNode(new Uri("http://www.dotnetrdf.org/configuration#")),
                g.CreateUriNode(new Uri("http://www.dotnetrdf.org/Configuration#")),
                g.CreateUriNode(new Uri("mailto:[email protected]")),
                u
            };

            this.ShowOrdering(nodes);

            this.CheckCombinations(nodes);
        }
Beispiel #25
0
 /// <summary>
 /// Nodes must implement an Equals method so we can do type specific equality
 /// </summary>
 /// <param name="other">Node to check for equality</param>
 /// <returns></returns>
 /// <remarks>
 /// Nodes implementations are also required to implement an override of the non-generic Equals method.  Standard implementations of some equality comparisons can be found in <see cref="EqualityHelper">EqualityHelper</see>
 /// </remarks>
 public abstract bool Equals(IBlankNode other);
Beispiel #26
0
 private void WriteInternalID(IBlankNode node)
 {
     this.writer.WriteAttributeString(RdfXml.Prefix, RdfXml.NodeId, RdfXml.Namespace, node.InternalID);
 }
 public bool Equals(IBlankNode other)
 {
     return(_source.Equals(other));
 }
Beispiel #28
0
 /// <summary>
 /// Nodes must implement a CompareTo method to allow them to be Sorted
 /// </summary>
 /// <param name="other">Node to compare self to</param>
 /// <returns></returns>
 /// <remarks>
 /// Implementations should use the SPARQL Term Sort Order for ordering nodes (as opposed to value sort order).  Standard implementations of Node type specific comparisons can be found in <see cref="ComparisonHelper">ComparisonHelper</see>
 /// </remarks>
 public abstract int CompareTo(IBlankNode other);
 /// <summary>
 /// Formats a Blank Node as a String.
 /// </summary>
 /// <param name="b">Blank Node.</param>
 /// <param name="segment">Triple Segment.</param>
 /// <returns></returns>
 protected override string FormatBlankNode(IBlankNode b, TripleSegment?segment)
 {
     return("_:" + _bnodeMapper.GetOutputID(b.InternalID));
 }
Beispiel #30
0
 /// <summary>
 /// Nodes must implement an Equals method so we can do type specific equality
 /// </summary>
 /// <param name="other">Node to check for equality</param>
 /// <returns></returns>
 /// <remarks>
 /// Nodes implementations are also required to implement an override of the non-generic Equals method.  Standard implementations of some equality comparisons can be found in <see cref="EqualityHelper">EqualityHelper</see>
 /// </remarks>
 public abstract bool Equals(IBlankNode other);
 /// <summary>
 /// Formats a Blank Node as a String
 /// </summary>
 /// <param name="b">Blank Node</param>
 /// <param name="segment">Triple Segment</param>
 /// <returns></returns>
 protected override string FormatBlankNode(IBlankNode b, TripleSegment? segment)
 {
     return "_:" + this._bnodeMapper.GetOutputID(b.InternalID);
 }
Beispiel #32
0
 /// <summary>
 /// Formats a Blank Node by using the <strong>bif:rdf_make_iid_of_qname()</strong> function
 /// </summary>
 /// <param name="b">Blank Node</param>
 /// <param name="segment">Triple Segment</param>
 /// <returns></returns>
 protected override string FormatBlankNode(IBlankNode b, TripleSegment?segment)
 {
     //Use the bif:rdf_make_iid_of_qname('nodeID://bnode') function
     return("`bif:rdf_make_iid_of_qname('nodeID://" + b.InternalID + "')`");
 }