public virtual void TestStatementsWithNamedBNode()
        {
            BNode bNode = new BNode("node");
            TurtleWriter instance = CreateInstance();
            instance.Add(new Statement(bNode, "b", (Entity)"C"));
            instance.Close();

            string expected = bNode + " <b> <C>.";
            Assert.AreEqual(expected, writer.ToString());
        }
示例#2
0
        public void TestFormulaMultipleOccurences()
        {
            N3Writer instance = (N3Writer)CreateInstance();

            BNode statementId = new BNode();
            instance.Add(new Statement("S", "p", (Entity)"O", statementId));
            instance.Add(new Statement("MyTheory", "contains", statementId));
            instance.Add(new Statement(statementId, "is", (Entity)"True"));
            instance.Close();

            string expected = "<MyTheory> <contains> {<S> <p> <O>.}.\n{<S> <p> <O>.} <is> <True>.";
            Assert.AreEqual(expected, writer.ToString());
        }
示例#3
0
        public void TestFormulaSingleOccurence()
        {
            N3Writer instance = (N3Writer)CreateInstance();

            BNode statementXId = new BNode();
            BNode statementYId = new BNode();
            instance.Add(new Statement("S", "p", (Entity)"X", statementXId));
            instance.Add(new Statement("S", "p", (Entity)"Y", statementYId));
            instance.Add(new Statement(statementXId, Predicate.LogImplies, statementYId));
            instance.Close();

            string expected = "{<S> <p> <X>.} => {<S> <p> <Y>.}.";
            Assert.AreEqual(expected, writer.ToString());
        }
示例#4
0
        public void TestFormulaMixedWithRegularStatements()
        {
            N3Writer instance = (N3Writer)CreateInstance();

            BNode statementXId = new BNode();
            BNode statementYId = new BNode();
            instance.Add(new Statement("S", "b", (Entity)"B"));
            instance.Add(new Statement("S", "p", (Entity)"X", statementXId));
            instance.Add(new Statement("S", "p", (Entity)"Y", statementYId));
            instance.Add(new Statement(statementXId, Predicate.LogImplies, statementYId));
            instance.Close();

            string expected = "<S> <b> <B>.\n{<S> <p> <X>.} => {<S> <p> <Y>.}.";
            Assert.AreEqual(expected, writer.ToString());
        }
        public void TestWriteFormulaWithOneStatement()
        {
            NTriplesWriter instance = new NTriplesWriter(writer);

            BNode statementId = new BNode("s");
            instance.Add(new Statement("A", "b", (Entity)"C", statementId));
            instance.Close();

            string expected = "_:s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/10/swap/log#Formula>.\n" +
                              "_:s <http://www.w3.org/2000/10/swap/log#includes> _:bnode.\n" +
                              "_:bnode <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement>.\n" +
                              "_:bnode <http://www.w3.org/1999/02/22-rdf-syntax-ns#subject> <A>.\n" +
                              "_:bnode <http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate> <b>.\n" +
                              "_:bnode <http://www.w3.org/1999/02/22-rdf-syntax-ns#object> <C>.\n";
            Assert.AreEqual(expected, Regex.Replace(writer.ToString(), @"_:bnode\d+", "_:bnode"));
        }
示例#6
0
        public void TestFormulaWithinFormula()
        {
            N3Writer instance = (N3Writer)CreateInstance();

            BNode statementXId = new BNode();
            BNode statementYId = new BNode();
            BNode statementImplId = new BNode();
            instance.Add(new Statement("S", "p", (Entity)"X", statementXId));
            instance.Add(new Statement("S", "p", (Entity)"Y", statementYId));
            instance.Add(new Statement(statementXId, Predicate.LogImplies, statementYId, statementImplId));
            instance.Add(new Statement(statementImplId, Predicate.LogImplies, (Entity)"Truth"));
            instance.Close();

            string expected = "{\n{<S> <p> <X>.}\n=>\n{<S> <p> <Y>.}.\n} => <Truth>.";
            Assert.AreEqual(expected, writer.ToString());
        }
示例#7
0
    public static void Main()
    {
        // Create the instance data

        MemoryStore dataModel = new MemoryStore();

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

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

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

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

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

        dataModel.AddReasoner(engine);

        // Query the data model

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

        // Ask for the rdfs:labels of everyone.  Note that the data model
        // has foaf:names for the people, and the schema asserts that
        // foaf:name is a subproperty of rdfs:label.
        Console.WriteLine("People's labels:");
        foreach (Statement s in dataModel.Select(new Statement(null, rdfsLabel, null)))
            Console.WriteLine("\t" + s);
    }
示例#8
0
    public static void Main()
    {
        MemoryStore store = new MemoryStore();

        Entity computer = new Entity("http://example.org/computer");
        Entity says = "http://example.org/says";
        Entity wants = "http://example.org/wants";
        Entity desire = new BNode();
        Entity description = new Entity("http://example.org/description");

        store.Add(new Statement(computer, says, (Literal)"Hello world!"));
        store.Add(new Statement(computer, wants, desire));
        store.Add(new Statement(desire, description, (Literal)"to be human"));
        store.Add(new Statement(desire, RDF+"type", (Entity)"http://example.org/Desire"));

        using (RdfWriter writer = new RdfXmlWriter(Console.Out)) {
            writer.Namespaces.AddNamespace("http://example.org/", "ex");
            writer.Write(store);
        }
    }
示例#9
0
        public static void Add(StatementSink sink, Entity subject, string predicate, string type, string [] values)
        {
            if (values == null)
            {
                System.Console.WriteLine("{0} has no values; skipping", predicate);
                return;
            }

            Entity    empty = new SemWeb.BNode();
            Statement top   = new Statement(subject, (Entity)MetadataStore.Namespaces.Resolve(predicate), empty);
            Statement desc  = new Statement(empty,
                                            (Entity)MetadataStore.Namespaces.Resolve("rdf:type"),
                                            (Entity)MetadataStore.Namespaces.Resolve(type));

            sink.Add(desc);
            foreach (string value in values)
            {
                Statement literal = new Statement(empty,
                                                  (Entity)MetadataStore.Namespaces.Resolve("rdf:li"),
                                                  new SemWeb.Literal(value, null, null));
                sink.Add(literal);
            }
            sink.Add(top);
        }
示例#10
0
		private Entity GetBlankNode(string nodeID) {
			if (blankNodes.ContainsKey(nodeID))
				return (Entity)blankNodes[nodeID];
			
			Entity entity = new BNode(nodeID);
			blankNodes[nodeID] = entity;

			return entity;
		}
示例#11
0
		public static void AddLiteral (StatementSink sink, string predicate, string type, SemWeb.Literal value)
		{
			Entity empty = new BNode ();
			Statement top = new Statement (FSpotXMPBase, (Entity)MetadataStore.Namespaces.Resolve (predicate), empty);
			Statement desc = new Statement (empty, 
							(Entity)MetadataStore.Namespaces.Resolve ("rdf:type"), 
							(Entity)MetadataStore.Namespaces.Resolve (type));
			sink.Add (desc);
			Statement literal = new Statement (empty,
							   (Entity)MetadataStore.Namespaces.Resolve ("rdf:li"),
							   value);
			sink.Add (literal);
			sink.Add (top);
		}
示例#12
0
        public void TestFormulaWithMultipleStatementsSingleOccurence()
        {
            N3Writer instance = (N3Writer)CreateInstance();

            BNode formulaId = new BNode();
            BNode statementZId = new BNode();
            instance.Add(new Statement("S", "p", (Entity)"X", formulaId));
            instance.Add(new Statement("S", "p", (Entity)"Y", formulaId));
            instance.Add(new Statement("S", "p", (Entity)"Z", statementZId));
            instance.Add(new Statement(formulaId, Predicate.LogImplies, statementZId));
            instance.Close();

            string expected = "{\n <S> <p> <X>.\n <S> <p> <Y>.\n} => {<S> <p> <Z>.}.";
            Assert.AreEqual(expected, writer.ToString());
        }
示例#13
0
 public BNodeWrapper(BNode res)
 {
     r = res;
 }
示例#14
0
		public void SelectDirectory (ImageDirectory dir, StatementSink sink)
		{
			foreach (DirectoryEntry e in dir.Entries) {
#if DEBUG_LOADER
				System.Console.WriteLine ("{0}", e.Id);
#endif
				switch (e.Id) {
				case TagId.IPTCNAA:
					System.IO.Stream iptcstream = new System.IO.MemoryStream (e.RawData);
					FSpot.Iptc.IptcFile iptc = new FSpot.Iptc.IptcFile (iptcstream);
					iptc.Select (sink);
					break;
				case TagId.PhotoshopPrivate:
					System.IO.Stream bimstream = new System.IO.MemoryStream (e.RawData);
					FSpot.Bim.BimFile bim = new FSpot.Bim.BimFile (bimstream);
					bim.Select (sink);
					break;
				case TagId.XMP:
					System.IO.Stream xmpstream = new System.IO.MemoryStream (e.RawData);
					FSpot.Xmp.XmpFile xmp = new FSpot.Xmp.XmpFile (xmpstream);
					xmp.Select (sink);
					break;
				case TagId.ImageDescription:
					MetadataStore.AddLiteral (sink, "dc:description", "rdf:Alt", 
								  new Literal (e.ValueAsString [0], "x-default", null));
					break;
				case TagId.UserComment:
					MetadataStore.AddLiteral (sink, "exif:UserComment", "rdf:Alt", 
								  new Literal (e.ValueAsString [0], "x-default", null));
					break;
				case TagId.Copyright:
					MetadataStore.AddLiteral (sink, "dc:rights", "rdf:Alt", 
								  new Literal (e.ValueAsString [0], "x-default", null));
					break;
				case TagId.Artist:
					MetadataStore.Add (sink, "dc:creator", "rdf:Seq", e.ValueAsString);
					break;
				case TagId.ExifIfdPointer:
					try {
						ImageDirectory sub = ((SubdirectoryEntry)e).Directory [0];
						SelectDirectory (sub, sink);
					} catch (System.Exception exc) {
						System.Console.WriteLine (exc);
					}
					break;
				case TagId.Software:
					MetadataStore.AddLiteral (sink, "xmp:CreatorTool", e.ValueAsString [0]);
					break;
				case TagId.DateTime:
					try {

					MetadataStore.AddLiteral (sink, "xmp:ModifyDate", 
								  e.ValueAsDate.ToString ("yyyy-MM-ddThh:mm:ss"));
					} catch (System.Exception ex) {
						System.Console.WriteLine (String.Format ("error parsing {0}{2}{1}", e.ValueAsString[0], ex, Environment.NewLine));
					}

					break;
				case TagId.DateTimeOriginal:
				case TagId.DateTimeDigitized:
					// FIXME subsectime needs to be included in these values
					// FIXME shouldn't DateTimeOriginal be xmp:CreateDate? the spec says no but wtf?
					try {
						MetadataStore.AddLiteral (sink, "exif:" + e.Id.ToString (), 
									  e.ValueAsDate.ToString ("yyyy-MM-ddThh:mm:ss"));
					} catch (System.Exception ex) {
						System.Console.WriteLine (String.Format ("error parsing {0}{2}{1}", e.ValueAsString[0], ex, Environment.NewLine));
					}
					break;
					//case TagId.SpatialFrequencyResponse
				case TagId.ExifCFAPattern:
					CFAPattern pattern = new CFAPattern (e.RawData, e.IsLittle);
					Entity empty = new BNode ();
					Statement top = new Statement (MetadataStore.FSpotXMPBase, 
								       (Entity)MetadataStore.Namespaces.Resolve ("exif:" + e.Id.ToString ()),
								       empty);
					
					Statement cols = new Statement (empty, 
									(Entity) MetadataStore.Namespaces.Resolve ("exif:Columns"),
									new Literal (pattern.Columns.ToString (), null, null));
					sink.Add (cols);
					Statement rows = new Statement (empty, 
									(Entity) MetadataStore.Namespaces.Resolve ("exif:Rows"),
									new Literal (pattern.Rows.ToString (), null, null));
					sink.Add (rows);
					string [] vals = e.ArrayToString (pattern.Values);
					MetadataStore.Add (sink, empty, "exif:Values", "rdf:Seq", vals);
					sink.Add (top);
					break;
				case TagId.ExifVersion:
				case TagId.FlashPixVersion:
				case TagId.ColorSpace:
				case TagId.CompressedBitsPerPixel:
				case TagId.PixelYDimension:
				case TagId.PixelXDimension:
				case TagId.RelatedSoundFile:
				case TagId.ExposureTime:
				case TagId.FNumber:
				case TagId.ExposureProgram:
				case TagId.SpectralSensitivity:
				case TagId.ShutterSpeedValue:
				case TagId.ApertureValue:
				case TagId.BrightnessValue:
				case TagId.ExposureBiasValue:
				case TagId.MaxApertureValue:
				case TagId.SubjectDistance:
				case TagId.MeteringMode:
				case TagId.LightSource:
				case TagId.FocalLength:
				case TagId.FlashEnergy:
				case TagId.FocalPlaneXResolution:
				case TagId.FocalPlaneYResolution:
				case TagId.FocalPlaneResolutionUnit:
				case TagId.ExposureIndex:
				case TagId.SensingMethod:
				case TagId.FileSource:
				case TagId.SceneType:
				case TagId.CustomRendered:
				case TagId.ExposureMode:
				case TagId.WhiteBalance:
				case TagId.DigitalZoomRatio:
				case TagId.FocalLengthIn35mmFilm:
				case TagId.SceneCaptureType:
				case TagId.GainControl:
				case TagId.Contrast:
				case TagId.Saturation:
				case TagId.Sharpness:
					MetadataStore.AddLiteral (sink, "exif:" + e.Id.ToString (), e.ValueAsString [0]);
					break;
				case TagId.ComponentsConfiguration:
				case TagId.ISOSpeedRatings:
				case TagId.SubjectArea:
				case TagId.SubjectLocation:
					MetadataStore.Add (sink, "exif:" + e.Id.ToString (), "rdf:Seq", e.ValueAsString);
					break;
				case TagId.TransferFunction:
				case TagId.YCbCrSubSampling:
				case TagId.WhitePoint:
				case TagId.PrimaryChromaticities:
				case TagId.YCbCrCoefficients:
				case TagId.ReferenceBlackWhite:
				case TagId.BitsPerSample:
					MetadataStore.Add (sink, "tiff:" + e.Id.ToString (), "rdf:Seq", e.ValueAsString);
					break;
				case TagId.Orientation:
				case TagId.Compression:
				case TagId.PhotometricInterpretation:					
				case TagId.SamplesPerPixel:
				case TagId.PlanarConfiguration:
				case TagId.YCbCrPositioning:
				case TagId.ResolutionUnit:
				case TagId.ImageWidth:
				case TagId.ImageLength:
				case TagId.Model:
				case TagId.Make:
					MetadataStore.AddLiteral (sink, "tiff:" + e.Id.ToString (), e.ValueAsString [0]);
					break;
				}
			}
		}
        private Resource ReadResource2(ParseContext context, out bool reverse)
        {
            reverse = false;

            Location loc = context.Location;

            object tok = ReadToken(context.source, context);

            if (tok is Literal)
            {
                return((Literal)tok);
            }

            string str = (string)tok;

            if (str == "")
            {
                return(null);
            }

            // @ Keywords

            if (str == "@prefix")
            {
                return(PrefixResource);
            }

            if (str == "@keywords")
            {
                return(KeywordsResource);
            }

            if (context.UsingKeywords && context.Keywords.Contains(str))
            {
                str = "@" + str;
            }
            if (!context.UsingKeywords &&
                (str == "a" || str == "has" || str == "is"))
            {
                str = "@" + str;
            }

            // Standard Keywords
            // TODO: Turn these off with @keywords

            if (str == "@a")
            {
                return(entRDFTYPE);
            }

            if (str == "=")
            {
                return(entDAMLEQUIV);
            }
            if (str == "=>")
            {
                return(entLOGIMPLIES);
            }
            if (str == "<=")
            {
                reverse = true;
                return(entLOGIMPLIES);
            }

            if (str == "@has")             // ignore this token
            {
                return(ReadResource2(context, out reverse));
            }

            if (str == "@is")
            {
                // Reverse predicate
                bool     reversetemp;
                Resource pred = ReadResource2(context, out reversetemp);
                reverse = true;

                string of = ReadToken(context.source, context) as string;
                if (of == null)
                {
                    OnError("End of stream while expecting 'of'", loc);
                }
                if (of == "@of" ||
                    (!context.UsingKeywords && of == "of") ||
                    (context.UsingKeywords && context.Keywords.Contains("of") && of == "of"))
                {
                    return(pred);
                }
                OnError("Expecting token 'of' but found '" + of + "'", loc);
                return(null);                // unreachable
            }

            if (str.StartsWith("@"))
            {
                OnError("The " + str + " directive is not supported", loc);
            }

            // URI

            if (str.StartsWith("<") && str.EndsWith(">"))
            {
                string uri = GetAbsoluteUri(BaseUri, str.Substring(1, str.Length - 2));
                return(GetResource(context, uri));
            }

            // VARIABLE

            if (str[0] == '?')
            {
                string name = str.Substring(1);
                Entity var  = (Entity)context.variables[name];
                if (var == null)
                {
                    var = new Variable(name);
                    AddVariable((Variable)var);
                    context.variables[name] = var;
                }
                return(var);
            }

            // QNAME

            if (str.IndexOf(":") != -1)
            {
                return(ResolveQName(str, context, loc));
            }

            // ANONYMOUS

            if (str == "[")
            {
                Entity ret = new BNode();
                ReadWhitespace(context.source);
                if (context.source.Peek() != ']')
                {
                    char bracket = ReadPredicates(ret, context);
                    if (bracket == '.')
                    {
                        bracket = ReadPunc(context.source);
                    }
                    if (bracket != ']')
                    {
                        OnError("Expected a close bracket but found '" + bracket + "'", loc);
                    }
                }
                else
                {
                    context.source.Read();
                }
                return(ret);
            }

            // LIST

            if (str == "(")
            {
                // A list
                Entity ent = null;
                while (true)
                {
                    bool     rev2;
                    Resource res = ReadResource(context, out rev2);
                    if (res == null)
                    {
                        break;
                    }

                    if (ent == null)
                    {
                        ent = new BNode();
                    }
                    else
                    {
                        Entity sub = new BNode();
                        Add(context.store, new Statement(ent, entRDFREST, sub, context.meta), loc);
                        ent = sub;
                    }

                    Add(context.store, new Statement(ent, entRDFFIRST, res, context.meta), loc);
                }
                if (ent == null)                 // No list items.
                {
                    ent = entRDFNIL;             // according to Turtle spec
                }
                else
                {
                    Add(context.store, new Statement(ent, entRDFREST, entRDFNIL, context.meta), loc);
                }
                return(ent);
            }

            if (str == ")")
            {
                return(null);                // Should I use a more precise end-of-list return value?
            }
            // FORMULA

            if (str == "{")
            {
                // ParseContext is a struct, so this gives us a clone.
                ParseContext newcontext = context;

                // The formula is denoted by a blank node
                newcontext.meta = new BNode();

                // According to the spec, _:xxx anonymous nodes are
                // local to the formula.  But ?$variables (which aren't
                // mentioned in the spec) are treated as global names.
                newcontext.anonymous = new Hashtable();

                while (NextPunc(context.source) != '}' && ReadStatement(newcontext))
                {
                }
                ReadWhitespace(context.source);
                if (context.source.Peek() == '}')
                {
                    context.source.Read();
                }

                return(newcontext.meta);
            }

            // NUMERIC LITERAL

            // In Turtle, numbers are restricted to [0-9]+, and are datatyped xsd:integer.
            double numval;

            if (double.TryParse(str, System.Globalization.NumberStyles.Any, null, out numval))
            {
                return(new Literal(numval.ToString()));
            }

            // If @keywords is used, alphanumerics that aren't keywords
            // are local names in the default namespace.
            if (context.UsingKeywords && char.IsLetter(str[0]))
            {
                if (BaseUri == null)
                {
                    OnError("The document contains an unqualified name but no BaseUri was specified: \"" + str + "\"", loc);
                }
                return(GetResource(context, BaseUri + str));
            }

            // NOTHING MATCHED

            OnError("Invalid token: " + str, loc);
            return(null);
        }
示例#16
0
		public void Select (SemWeb.StatementSink sink)
		{
			Entity keywords = null;

			foreach (DataSet data in sets) {
				switch (data.ID) {
				case DataSetID.CopyrightNotice:
					MetadataStore.AddLiteral (sink, "dc:rights", "rdf:Alt", new SemWeb.Literal (data.XmpObject, "x-default", null));
					break;
				case DataSetID.ByLine:
					MetadataStore.AddLiteral (sink, "dc:creator", "rdf:Seq", new SemWeb.Literal (data.XmpObject, "x-default", null));
					break;
				case DataSetID.CaptionAbstract:
					MetadataStore.AddLiteral (sink, "dc:description", "rdf:Alt", new SemWeb.Literal (data.XmpObject, "x-default", null));
					break;
				case DataSetID.ObjectName:
					MetadataStore.AddLiteral (sink, "dc:title", "rdf:Alt", new SemWeb.Literal (data.XmpObject, "x-default", null));
					break;
				case DataSetID.Keywords:
					if (keywords == null) {
						keywords = new BNode ();
						sink.Add (new Statement (MetadataStore.FSpotXMPBase, 
									 MetadataStore.Namespaces.Resolve ("dc:subject"),
									 keywords)); 
						sink.Add (new Statement (keywords, 
									 (Entity)MetadataStore.Namespaces.Resolve ("rdf:type"),
									 (Entity)MetadataStore.Namespaces.Resolve ("rdf:Bag")));
					}
					sink.Add (new Statement (keywords, 
								 MetadataStore.Namespaces.Resolve ("rdf:li"), 
								 new SemWeb.Literal (data.XmpObject, "x-default", null)));
					break;
				default:
					if (data.XmpPredicate != null) {
						sink.Add (new Statement (MetadataStore.FSpotXMPBase, 
									 (Entity)data.XmpPredicate, 
									 new SemWeb.Literal (data.XmpObject)));
					}
					break;
				}
			}
		}
示例#17
0
        public void TestListWithZeroElements()
        {
            N3Writer instance = (N3Writer)CreateInstance();

            BNode listId = new BNode();
            instance.Add(new Statement(listId, Predicate.RdfType, (Entity)"List"));
            instance.Add(new Statement(listId, Predicate.RdfFirst, Identifier.RdfNil));
            instance.Add(new Statement(listId, Predicate.RdfRest, Identifier.RdfNil));
            instance.Close();

            string expected = "() a <List>.";
            Assert.AreEqual(expected, writer.ToString());
        }
示例#18
0
 /// <summary>
 /// Writes the specified bNode to the output writer.
 /// </summary>
 /// <param name="bNode">The bNode.</param>
 protected virtual void WriteBNode(BNode bNode)
 {
     Write("_:");
     WriteEscaped(bNode.LocalName ?? ("bnode" + Math.Abs(bNode.GetHashCode())));
 }
示例#19
0
		private Resource ResolveQName(string str, ParseContext context, Location loc) {
			int colon = str.IndexOf(":");
			string prefix = str.Substring(0, colon);
			if (prefix == "_") {
				Resource ret = (Resource)context.anonymous[str];
				if (ret == null) {
					ret = new BNode(str.Substring(colon+1));
					context.anonymous[str] = ret;
				}
				return ret;
			} else if (prefix == "" && context.namespaces.GetNamespace(prefix) == null) {
				return GetResource(context, (BaseUri == null ? "#" : BaseUri) + str.Substring(colon+1));
			} else {
				string ns = context.namespaces.GetNamespace(prefix);
				if (ns == null)
					OnError("Prefix is undefined: " + str, loc);
				if (prefix != "")
					Namespaces.AddNamespace(ns, prefix);
				return GetResource(context, ns + str.Substring(colon+1));
			}
		}
示例#20
0
        public void TestListWithThreeElementsWithLastUnbound()
        {
            N3Writer instance = (N3Writer)CreateInstance();

            BNode listId = new BNode();
            BNode listTwoId = new BNode();
            BNode listThreeId = new BNode();
            instance.Add(new Statement(listId, Predicate.RdfType, (Entity)"List"));
            instance.Add(new Statement(listId, Predicate.RdfFirst, (Entity)"A"));
            instance.Add(new Statement(listId, Predicate.RdfRest, listTwoId));
            instance.Add(new Statement(listTwoId, Predicate.RdfFirst, (Entity)"B"));
            instance.Add(new Statement(listTwoId, Predicate.RdfRest, listThreeId));
            instance.Add(new Statement(listThreeId, Predicate.RdfFirst, (Entity)"C"));
            instance.Close();

            string expected = @"\(<A> <B> <C> _:bnode\d+\) a <List>.";
            Assert.That(writer.ToString(), Text.Matches(expected));
        }
示例#21
0
        public void TestListWithFormulaElements()
        {
            N3Writer instance = (N3Writer)CreateInstance();

            BNode statementXId = new BNode();
            BNode statementYId = new BNode();
            BNode statementZId = new BNode();
            instance.Add(new Statement("S", "p", (Entity)"X", statementXId));
            instance.Add(new Statement("S", "p", (Entity)"Y", statementYId));
            instance.Add(new Statement("S", "p", (Entity)"Z", statementZId));

            BNode listId = new BNode();
            BNode listTwoId = new BNode();
            BNode listThreeId = new BNode();
            instance.Add(new Statement(listId, Predicate.RdfType, (Entity)"List"));
            instance.Add(new Statement(listId, Predicate.RdfFirst, statementXId));
            instance.Add(new Statement(listId, Predicate.RdfRest, listTwoId));
            instance.Add(new Statement(listTwoId, Predicate.RdfFirst, statementYId));
            instance.Add(new Statement(listTwoId, Predicate.RdfRest, listThreeId));
            instance.Add(new Statement(listThreeId, Predicate.RdfFirst, statementZId));
            instance.Add(new Statement(listThreeId, Predicate.RdfRest, Identifier.RdfNil));
            instance.Close();

            string expected = "({<S> <p> <X>.}\n {<S> <p> <Y>.}\n {<S> <p> <Z>.}) a <List>.";
            Assert.AreEqual(expected, writer.ToString());
        }
示例#22
0
		private Entity ParseDescription() {
			// The XmlReader is positioned on an element node
			// that is a description of an entity.
			// On returning, the reader is positioned after the
			// end element of the description node.
			
			string nodeID = xml.GetAttribute("nodeID", NS.RDF);
			string about = xml.GetAttribute("about", NS.RDF);
			string ID = xml.GetAttribute("ID", NS.RDF);
			if (isset(nodeID) + isset(about) + isset(ID) > 1)
				OnError("An entity description cannot specify more than one of rdf:nodeID, rdf:about, and rdf:ID");

			if (nodeID != null && !IsValidXmlName(nodeID))
				OnWarning("'" + nodeID + "' is not a valid XML Name");
			if (ID != null && !IsValidXmlName(ID))
				OnWarning("'" + ID + "' is not a valid XML Name");
				
			Entity entity;
			
			if (about != null)
				entity = GetNamedNode(Unrelativize(about));
			else if (ID != null) {
				entity = GetNamedNode(Unrelativize("#" + ID));
				
				if (seenIDs.ContainsKey(entity.Uri))
					OnWarning("Two descriptions should not use the same rdf:ID: <" + entity.Uri + ">");
				seenIDs[entity.Uri] = seenIDs;
			} else if (nodeID != null)
				entity = GetBlankNode(nodeID);
			else
				entity = new BNode();
			
			// If the name of the element is not rdf:Description,
			// then the name gives its type.
			string curnode = CurNode();
			if (curnode != NS.RDF + "Description") {
				if (IsRestrictedName(curnode) || IsDeprecatedName(curnode))
					OnError(xml.Name + " cannot be the type of a resource.");
				if (curnode == NS.RDF + "li") OnError("rdf:li cannot be the type of a resource");
				storage.Add(new Statement(entity, rdfType, (Entity)curnode, Meta));
			}
			
			ParsePropertyAttributes(entity);
			ParsePropertyNodes(entity);
			
			return entity;
		}
示例#23
0
    public static void Main()
    {
        // Create the instance data

        MemoryStore dataModel = new MemoryStore();

        BNode paris = new BNode("paris");
        BNode orleans = new BNode("orleans");
        BNode chartres = new BNode("chartres");
        BNode amiens = new BNode("amiens");
        BNode blois = new BNode("blois");
        BNode bourges = new BNode("bourges");
        BNode tours = new BNode("tours");
        BNode lemans = new BNode("lemans");
        BNode angers = new BNode("angers");
        BNode nantes = new BNode("nantes");

        Entity oneway = new Entity("http://www.agfa.com/w3c/euler/graph.axiom#oneway");
        Entity path = new Entity("http://www.agfa.com/w3c/euler/graph.axiom#path");

        dataModel.Add(new Statement(paris, oneway, orleans));
        dataModel.Add(new Statement(paris, oneway, chartres));
        dataModel.Add(new Statement(paris, oneway, amiens));
        dataModel.Add(new Statement(orleans, oneway, blois));
        dataModel.Add(new Statement(orleans, oneway, bourges));
        dataModel.Add(new Statement(blois, oneway, tours));
        dataModel.Add(new Statement(chartres, oneway, lemans));
        dataModel.Add(new Statement(lemans, oneway, angers));
        dataModel.Add(new Statement(lemans, oneway, tours));
        dataModel.Add(new Statement(angers, oneway, nantes));

        // Create the inference rules by reading them from a N3 string.

        string rules =
            "@prefix : <http://www.agfa.com/w3c/euler/graph.axiom#>.\n" +
            "\n" +
            "{ ?a :oneway ?b } => { ?a :path ?b } .\n" +
            "{ ?a :path ?b . ?b :path ?c . } => { ?a :path ?c } .\n";

        // Create our question in the form of a statement to test.

        Statement question = new Statement(paris, path, nantes);

        // Create the Euler engine

        Euler engine = new Euler(new N3Reader(new StringReader(rules)));

        // First Method of Inference:
        // Ask the engine whether there is a path from paris to nantes.
        // The Prove method will return a list of proofs, or an empty
        // array if it could not find a proof.

        foreach (Proof p in engine.Prove(dataModel, new Statement[] { question })) {
            Console.WriteLine(p.ToString());
        }

        // Second Method of Inference:
        // Apply the engine to the data model and then use the data
        // model's Contains method to see if the statement is "in"
        // the model + reasoning.

        dataModel.AddReasoner(engine);

        Console.WriteLine("Euler Says the Question is: " + dataModel.Contains(question));
    }
示例#24
0
		private void ParseProperty(Entity subject, ref int liIndex) {
			// The reader is positioned on a propert node,
			// and on returning the reader is positioned past
			// that node.
			
			// Get all of the attributes before we move the reader forward.
			
			string nodeID = xml.GetAttribute("nodeID", NS.RDF);
			string resource = xml.GetAttribute("resource", NS.RDF);
			
			string parseType = xml.GetAttribute("parseType", NS.RDF);
			string datatype = xml.GetAttribute("datatype", NS.RDF);
			
			string lang = xml.XmlLang != "" ? xml.XmlLang : null;

			string predicate = CurNode();
			if (predicate == NS.RDF + "li")
				predicate = NS.RDF + "_" + (liIndex++);

			if (IsRestrictedName(predicate))
				OnError(xml.Name + " cannot be used as a property name.");
			if (IsDeprecatedName(predicate))
				OnError(xml.Name + " has been deprecated and cannot be used as a property name.");

			string ID = xml.GetAttribute("ID", NS.RDF);

			if (nodeID != null && !IsValidXmlName(nodeID))
				OnWarning("'" + nodeID + "' is not a valid XML Name");
			if (ID != null && !IsValidXmlName(ID))
				OnWarning("'" + ID + "' is not a valid XML Name");
				
			Resource objct = null;
			if (nodeID != null || resource != null) {
				if (isset(nodeID) + isset(resource) > 1)
					OnError("A predicate node cannot specify more than one of rdf:nodeID and rdf:resource");
					
				if (parseType != null || datatype != null)
					OnError("The attributes rdf:parseType and rdf:datatype are not valid on a predicate with a rdf:nodeID or rdf:resource attribute");
					
				// Object is an entity given by nodeID or resource.
				if (nodeID != null)
					objct = GetBlankNode(nodeID);
				else if (resource != null)
					objct = GetNamedNode(Unrelativize(resource));
					
				ParsePropertyAttributes((Entity)objct);
				
				// No children are allowed in this element.
				if (!xml.IsEmptyElement)
				while (xml.Read()) {
					if (xml.NodeType == XmlNodeType.EndElement) break;
					if (xml.NodeType == XmlNodeType.Whitespace) continue;
					if (xml.NodeType == XmlNodeType.Comment) continue;
					if (xml.NodeType == XmlNodeType.ProcessingInstruction) continue;
					OnError("Content is not allowed within a property with a rdf:nodeID or rdf:resource attribute");
				}
			
			} else if (parseType != null && parseType == "Literal") {
				if (datatype != null)
					OnError("The attribute rdf:datatype is not valid on a predicate whose parseType is Literal.");

				datatype = "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral";
				
				if (ParsePropertyAttributes(new BNode()))
					OnError("Property attributes are not valid when parseType is Literal");

				// TODO: Do we canonicalize according to:
				// http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/ ?
				
				objct = new Literal(xml.ReadInnerXml(), null, datatype);

			} else if (parseType != null && parseType == "Resource") {
				objct = new BNode();
				
				ParsePropertyAttributes((Entity)objct);
				if (!xml.IsEmptyElement)
					ParsePropertyNodes((Entity)objct);
				
			} else if (parseType != null && parseType == "Collection") {
				Entity collection = new BNode();
				Entity lastnode = collection;
				bool empty = true;
				
				ParsePropertyAttributes(collection);
				
				if (!xml.IsEmptyElement)
				while (xml.Read()) {
					if (xml.NodeType == XmlNodeType.EndElement) break;
					if (xml.NodeType != XmlNodeType.Element) continue;
					
					if (!empty) {
						Entity next = new BNode();
						storage.Add(new Statement(lastnode, rdfRest, next, Meta));
						lastnode = next;
					}
					
					Entity item = ParseDescription();
					storage.Add(new Statement(lastnode, rdfFirst, item, Meta));
					
					empty = false;
				}

				storage.Add(new Statement(lastnode, rdfRest, rdfNil, Meta));
				
				if (empty)
					objct = rdfNil;
				else
					objct = collection;
					
			} else if (parseType != null) {
				OnError("Invalid value for parseType: '" + parseType + "'");
				
			} else if (datatype != null) {
				// Note that any xml:lang is discarded.
				
				if (ParsePropertyAttributes(new BNode()))
					OnError("Property attributes are not valid when a datatype is given");
					
				if (xml.IsEmptyElement) {
					objct = new Literal("", null, datatype);
				} else {
					#if !DOTNET2
					objct = new Literal(xml.ReadString(), null, datatype);
					#else
					objct = new Literal(xml.ReadElementContentAsString(), null, datatype);
					#endif
					if (xml.NodeType != XmlNodeType.EndElement)
						OnError("XML markup may not appear in a datatyped literal property.");
				}
			
			} else {
				// We don't know whether the contents of this element
				// refer to a literal or an entity.  If an element is
				// a child of this node, then it must be an entity.
				// If the property has predicate attributes, then it
				// is an anonymous entity.  Otherwise the text content
				// is the literal value.
				
				objct = new BNode();
				if (ParsePropertyAttributes((Entity)objct)) {
					// Found property attributes.  There should be no other internal content?
					
					if (!xml.IsEmptyElement)
					while (xml.Read()) {
						if (xml.NodeType == XmlNodeType.EndElement) break;
						if (xml.NodeType == XmlNodeType.Whitespace) continue;
						if (xml.NodeType == XmlNodeType.Comment) continue;
						if (xml.NodeType == XmlNodeType.ProcessingInstruction) continue;
						OnError(xml.NodeType + " is not allowed within a property with property attributes");
					}
					
				} else {
					StringBuilder textcontent = new StringBuilder();
					bool hadText = false;
					bool hadElement = false;
					
					if (!xml.IsEmptyElement)
					while (xml.Read()) {
						if (xml.NodeType == XmlNodeType.EndElement) break;
						if (xml.NodeType == XmlNodeType.Element) {
							if (hadText)
								OnError("Both text and elements are present as a property value");
							if (hadElement)
								OnError("A property node cannot contain more than one entity description.  " + objct + " already found.");
							
							hadElement = true;
							
							objct = ParseDescription();
							
						} else if (xml.NodeType == XmlNodeType.Text || xml.NodeType == XmlNodeType.SignificantWhitespace) {
							if (hadElement)
								OnError("Both text and elements are present as a property value");
							textcontent.Append(xml.Value);
							hadText = true;
						} else {
							textcontent.Append(xml.Value);
						}
					}
					
					if (!hadElement)
						objct = new Literal(textcontent.ToString(), lang, null);
				}
			}
				
			storage.Add(new Statement(subject, predicate, objct, Meta));
			
			if (ID != null) {
				// In addition to adding the statement as normal, also
				// add a reified statement.
				Entity statement = GetNamedNode(Unrelativize("#" + ID));;
				storage.Add(new Statement(statement, rdfType, rdfStatement, Meta));
				storage.Add(new Statement(statement, rdfSubject, subject, Meta));
				storage.Add(new Statement(statement, rdfPredicate, (Entity)predicate, Meta));
				storage.Add(new Statement(statement, rdfObject, objct, Meta));
			}
		}
示例#25
0
 /// <summary>
 /// Writes the specified bNode to the output writer.
 /// </summary>
 /// <param name="bNode">The bNode.</param>
 protected virtual void WriteBNode(BNode bNode)
 {
     Write("_:");
     WriteEscaped(bNode.LocalName ?? ("bnode" + Math.Abs(bNode.GetHashCode())));
 }
示例#26
0
 public Entity ToEntity(name.levering.ryan.sparql.common.Value ent)
 {
     if (ent == null) return null;
     if (ent is BNodeWrapper) return ((BNodeWrapper)ent).r;
     if (ent is URIWrapper) return ((URIWrapper)ent).r;
     if (ent is name.levering.ryan.sparql.common.BNode) {
         name.levering.ryan.sparql.common.BNode bnode = (name.levering.ryan.sparql.common.BNode)ent;
         Entity r = (Entity)bnodes[bnode.getID()];
         if (r == null) {
             r = new BNode();
             bnodes[bnode.getID()] = r;
         }
         return r;
     } else if (ent is name.levering.ryan.sparql.common.URI) {
         name.levering.ryan.sparql.common.URI uri = (name.levering.ryan.sparql.common.URI)ent;
         return new Entity(uri.getURI());
     } else {
         return null;
     }
 }
示例#27
0
 void CanForgetBNodes.ForgetBNode(BNode bnode)
 {
     anonNames.Remove(bnode);
     anonNameMap.Remove(bnode);
 }
示例#28
0
 /// <summary>
 /// Writes the specified bNode to the output writer.
 /// </summary>
 /// <param name="bNode">The bNode.</param>
 protected override void WriteBNode(BNode bNode)
 {
     if (bNode is Variable)
         WriteVariable((Variable)bNode);
     else
         base.WriteBNode(bNode);
 }
示例#29
0
        private void ParseProperty(Entity subject, ref int liIndex)
        {
            // The reader is positioned on a propert node,
            // and on returning the reader is positioned past
            // that node.

            // Get all of the attributes before we move the reader forward.

            string nodeID   = xml.GetAttribute("nodeID", NS.RDF);
            string resource = xml.GetAttribute("resource", NS.RDF);

            string parseType = xml.GetAttribute("parseType", NS.RDF);
            string datatype  = xml.GetAttribute("datatype", NS.RDF);

            string lang = xml.XmlLang != "" ? xml.XmlLang : null;

            string predicate = CurNode();

            if (predicate == NS.RDF + "li")
            {
                predicate = NS.RDF + "_" + (liIndex++);
            }

            if (IsRestrictedName(predicate))
            {
                OnError(xml.Name + " cannot be used as a property name");
            }
            if (IsDeprecatedName(predicate))
            {
                OnError(xml.Name + " has been deprecated and cannot be used as a property name");
            }

            string ID = xml.GetAttribute("ID", NS.RDF);

            if (nodeID != null && !IsValidXmlName(nodeID))
            {
                OnWarning("'" + nodeID + "' is not a valid XML Name");
            }
            if (ID != null && !IsValidXmlName(ID))
            {
                OnWarning("'" + ID + "' is not a valid XML Name");
            }

            Resource objct = null;

            if (nodeID != null || resource != null)
            {
                if (isset(nodeID) + isset(resource) > 1)
                {
                    OnError("A predicate node cannot specify more than one of rdf:nodeID and rdf:resource");
                }

                if (parseType != null || datatype != null)
                {
                    OnError("The attributes rdf:parseType and rdf:datatype are not valid on a predicate with a rdf:nodeID or rdf:resource attribute");
                }

                // Object is an entity given by nodeID or resource.
                if (nodeID != null)
                {
                    objct = GetBlankNode(nodeID);
                }
                else if (resource != null)
                {
                    objct = GetNamedNode(Unrelativize(resource));
                }

                ParsePropertyAttributes((Entity)objct);

                // No children are allowed in this element.
                if (!xml.IsEmptyElement)
                {
                    while (xml.Read())
                    {
                        if (xml.NodeType == XmlNodeType.EndElement)
                        {
                            break;
                        }
                        if (xml.NodeType == XmlNodeType.Whitespace)
                        {
                            continue;
                        }
                        if (xml.NodeType == XmlNodeType.Comment)
                        {
                            continue;
                        }
                        if (xml.NodeType == XmlNodeType.ProcessingInstruction)
                        {
                            continue;
                        }
                        OnError("Content is not allowed within a property with a rdf:nodeID or rdf:resource attribute");
                    }
                }
            }
            else if (parseType != null && parseType == "Literal")
            {
                if (datatype != null)
                {
                    OnError("The attribute rdf:datatype is not valid on a predicate whose parseType is Literal");
                }

                datatype = "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral";

                if (ParsePropertyAttributes(new BNode()))
                {
                    OnError("Property attributes are not valid when parseType is Literal");
                }

                // TODO: Do we canonicalize according to:
                // http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/ ?

                objct = new Literal(xml.ReadInnerXml(), null, datatype);
                ValidateLiteral((Literal)objct);
            }
            else if (parseType != null && parseType == "Resource")
            {
                objct = new BNode();

                ParsePropertyAttributes((Entity)objct);
                if (!xml.IsEmptyElement)
                {
                    ParsePropertyNodes((Entity)objct);
                }
            }
            else if (parseType != null && parseType == "Collection")
            {
                Entity collection = new BNode();
                Entity lastnode   = collection;
                bool   empty      = true;

                ParsePropertyAttributes(collection);

                if (!xml.IsEmptyElement)
                {
                    while (xml.Read())
                    {
                        if (xml.NodeType == XmlNodeType.EndElement)
                        {
                            break;
                        }
                        if (xml.NodeType != XmlNodeType.Element)
                        {
                            continue;
                        }

                        if (!empty)
                        {
                            Entity next = new BNode();
                            storage.Add(new Statement(lastnode, rdfRest, next, Meta));
                            lastnode = next;
                        }

                        Entity item = ParseDescription();
                        storage.Add(new Statement(lastnode, rdfFirst, item, Meta));

                        empty = false;
                    }
                }

                storage.Add(new Statement(lastnode, rdfRest, rdfNil, Meta));

                if (empty)
                {
                    objct = rdfNil;
                }
                else
                {
                    objct = collection;
                }
            }
            else if (parseType != null)
            {
                OnError("Invalid value for parseType: '" + parseType + "'");
            }
            else if (datatype != null)
            {
                // Note that any xml:lang is discarded.

                if (ParsePropertyAttributes(new BNode()))
                {
                    OnError("Property attributes are not valid when a datatype is given");
                }

                if (xml.IsEmptyElement)
                {
                    objct = new Literal("", null, datatype);
                    ValidateLiteral((Literal)objct);
                }
                else
                {
                                        #if !DOTNET2
                    objct = new Literal(xml.ReadString(), null, datatype);
                    if (xml.NodeType != XmlNodeType.EndElement)
                    {
                        OnError("XML markup may not appear in a datatyped literal property");
                    }
                                        #else
                    try {
                        objct = new Literal(xml.ReadElementContentAsString(), null, datatype);
                    } catch (XmlException) {
                        OnError("XML markup may not appear in a datatyped literal property");
                    }
                                        #endif
                    ValidateLiteral((Literal)objct);
                }
            }
            else
            {
                // We don't know whether the contents of this element
                // refer to a literal or an entity.  If an element is
                // a child of this node, then it must be an entity.
                // If the property has predicate attributes, then it
                // is an anonymous entity.  Otherwise the text content
                // is the literal value.

                objct = new BNode();
                if (ParsePropertyAttributes((Entity)objct))
                {
                    // Found property attributes.  There should be no other internal content?

                    if (!xml.IsEmptyElement)
                    {
                        while (xml.Read())
                        {
                            if (xml.NodeType == XmlNodeType.EndElement)
                            {
                                break;
                            }
                            if (xml.NodeType == XmlNodeType.Whitespace)
                            {
                                continue;
                            }
                            if (xml.NodeType == XmlNodeType.Comment)
                            {
                                continue;
                            }
                            if (xml.NodeType == XmlNodeType.ProcessingInstruction)
                            {
                                continue;
                            }
                            OnError(xml.NodeType + " is not allowed within a property with property attributes");
                        }
                    }
                }
                else
                {
                    StringBuilder textcontent = new StringBuilder();
                    bool          hadText     = false;
                    bool          hadElement  = false;

                    if (!xml.IsEmptyElement)
                    {
                        while (xml.Read())
                        {
                            if (xml.NodeType == XmlNodeType.EndElement)
                            {
                                break;
                            }
                            if (xml.NodeType == XmlNodeType.Element)
                            {
                                if (hadText)
                                {
                                    OnError("Both text and elements are present as a property value");
                                }
                                if (hadElement)
                                {
                                    OnError("A property node cannot contain more than one entity description.  " + objct + " already found");
                                }

                                hadElement = true;

                                objct = ParseDescription();
                            }
                            else if (xml.NodeType == XmlNodeType.Text || xml.NodeType == XmlNodeType.SignificantWhitespace)
                            {
                                if (hadElement)
                                {
                                    OnError("Both text and elements are present as a property value");
                                }
                                textcontent.Append(xml.Value);
                                hadText = true;
                            }
                            else
                            {
                                textcontent.Append(xml.Value);
                            }
                        }
                    }

                    if (!hadElement)
                    {
                        objct = new Literal(textcontent.ToString(), lang, null);
                    }
                }
            }

            storage.Add(new Statement(subject, predicate, objct, Meta));

            if (ID != null)
            {
                // In addition to adding the statement as normal, also
                // add a reified statement.
                Entity statement = GetNamedNode(Unrelativize("#" + ID));;
                storage.Add(new Statement(statement, rdfType, rdfStatement, Meta));
                storage.Add(new Statement(statement, rdfSubject, subject, Meta));
                storage.Add(new Statement(statement, rdfPredicate, (Entity)predicate, Meta));
                storage.Add(new Statement(statement, rdfObject, objct, Meta));
            }
        }
示例#30
0
 private string GetBNodeRef(BNode node)
 {
     if (node.LocalName != null &&
         (nameAlloc[node.LocalName] == null || (BNode)nameAlloc[node.LocalName] == node)
         && !node.LocalName.StartsWith("bnode")) {
         nameAlloc[node.LocalName] = node; // ensure two different nodes with the same local name don't clash
         return node.LocalName;
     } else if (anonAlloc[node] != null) {
         return (string)anonAlloc[node];
     } else {
         string id = "bnode" + (anonCounter++);
         anonAlloc[node] = id;
         return id;
     }
 }
示例#31
0
			public Entity ToEntity(org.openrdf.model.Value ent) {
				if (ent == null) return null;
				if (ent is BNodeWrapper) return ((BNodeWrapper)ent).r;
				if (ent is URIWrapper) return ((URIWrapper)ent).r;
				if (ent is org.openrdf.model.BNode) {
					org.openrdf.model.BNode bnode = (org.openrdf.model.BNode)ent;
					Entity r = (Entity)bnodes[bnode.getID()];
					if (r == null) {
						r = new BNode();
						bnodes[bnode.getID()] = r;
					}
					return r;
				} else if (ent is org.openrdf.model.URI) {
					org.openrdf.model.URI uri = (org.openrdf.model.URI)ent;
					return new Entity(uri.toString());
				} else {
					return null;
				}
			}
示例#32
0
		public static void Add (StatementSink sink, Entity subject, string predicate, string type, string [] values)
		{
			if (values == null) {
				System.Console.WriteLine ("{0} has no values; skipping", predicate);
				return;
			}

                        Entity empty = new SemWeb.BNode();
			Statement top = new Statement (subject, (Entity)MetadataStore.Namespaces.Resolve (predicate), empty);
			Statement desc = new Statement (empty, 
							(Entity)MetadataStore.Namespaces.Resolve ("rdf:type"), 
							(Entity)MetadataStore.Namespaces.Resolve (type));
			sink.Add (desc);
			foreach (string value in values) {
				Statement literal = new Statement (empty,
								   (Entity)MetadataStore.Namespaces.Resolve ("rdf:li"),
								   new SemWeb.Literal (value, null, null));
				sink.Add (literal);
			}
			sink.Add (top);
		}
示例#33
0
		private Resource ReadResource2(ParseContext context, bool allowDirective, out bool reverse, out bool forgetBNode) {
			reverse = false;
			forgetBNode = false;
			
			Location loc = context.Location;
			
			object tok = ReadToken(context.source, context);
			if (tok is Literal)
				return (Literal)tok;
			
			string str = (string)tok;
			if (str == "")
				return null;
				
			// Directives
			
			if (str == "@prefix") {
				if (allowDirective)
					return PrefixResource;
				else
					OnError("The directive '" + str + "' is not allowed here", loc);
			}

			if (str == "@keywords") {
				if (allowDirective)
					return KeywordsResource;
				else
					OnError("The directive '" + str + "' is not allowed here", loc);
			}

			if (str == "@base") {
				if (allowDirective)
					return BaseResource;
				else
					OnError("The directive '" + str + "' is not allowed here", loc);
			}
			
			// @ Keywords

			if (context.UsingKeywords && context.Keywords.Contains(str))
				str = "@" + str;
			if (!context.UsingKeywords &&
				( str == "a" || str == "has" || str == "is"))
				str = "@" + str;
			
			// Standard Keywords
			// TODO: Turn these off with @keywords
			
			if (str == "@a")
				return entRDFTYPE;
				
			if (str == "=")
				return entDAMLEQUIV;
			if (str == "=>")
				return entLOGIMPLIES;
			if (str == "<=") {
				reverse = true;
				return entLOGIMPLIES;
			}
			if (str == "=:>") // SPECIAL EXTENSION!
				return entGRAPHCONTAINS;

			if (str == "@has") // ignore this token
				return ReadResource2(context, false, out reverse, out forgetBNode);
			
			if (str == "@is") {
				// Reverse predicate
				bool reversetemp;
				Resource pred = ReadResource2(context, false, out reversetemp, out forgetBNode);
				reverse = true;
				
				string of = ReadToken(context.source, context) as string;
				if (of == null) OnError("End of stream while expecting 'of'", loc);
				if (of == "@of"
					|| (!context.UsingKeywords && of == "of")
					|| (context.UsingKeywords && context.Keywords.Contains("of") && of == "of"))
					return pred;
				OnError("Expecting token 'of' but found '" + of + "'", loc);
				return null; // unreachable
			}
			
			if (str.StartsWith("@"))
				OnError("The " + str + " directive is not supported", loc);

			// URI
			
			if (str.StartsWith("<") && str.EndsWith(">")) {
				string uri = GetAbsoluteUri(BaseUri, str.Substring(1, str.Length-2));
				string urierror = Entity.ValidateUri(uri);
				if (urierror != null)
					OnWarning(urierror, loc);
				return GetResource(context, uri);
			}
			
			// VARIABLE
			
			if (str[0] == '?') {
				string name = str.Substring(1);
				Entity varb = (Entity)context.variables[name];
				if (varb == null) {
					varb = new Variable(name);
					AddVariable((Variable)varb);
					context.variables[name] = varb;
				}
				return varb;
			}
			
			// QNAME

			if (str.IndexOf(":") != -1)
				return ResolveQName(str, context, loc);
				
			// ANONYMOUS
			
			if (str == "[") {
				Entity ret = new BNode();
				ReadWhitespace(context.source);
				if (context.source.Peek() != ']') {
					char bracket = ReadPredicates(ret, context);
					if (bracket == '.')
						bracket = ReadPunc(context.source);
					if (bracket != ']')
						OnError("Expected a close bracket but found '" + bracket + "'", loc);
				} else {
					context.source.Read();
				}
				forgetBNode = true;
				return ret;
			}
			
			// LIST
			
			if (str == "(") {
				// A list
				Entity head = null, ent = null;
				while (true) {
					bool rev2, fb2;
					Resource res = ReadResource(context, false, out rev2, out fb2);
					if (res == null)
						break;
					
					if (ent == null) {
						ent = new BNode();
						head = ent;
					} else {
						Entity sub = new BNode();
						Add(context.store, new Statement(ent, entRDFREST, sub, context.meta), loc);
						ent = sub;
					}
					
					Add(context.store, new Statement(ent, entRDFFIRST, res, context.meta), loc);
					if (fb2) DoForget(res, context);
				}
				if (head == null) // No list items.
					head = entRDFNIL; // according to Turtle spec
				else
					Add(context.store, new Statement(ent, entRDFREST, entRDFNIL, context.meta), loc);
				
				return head;
			}
			
			if (str == ")")
				return null; // Should I use a more precise end-of-list return value?
			
			// FORMULA
			
			if (str == "{") {
				// ParseContext is a struct, so this gives us a clone.
				ParseContext newcontext = context;
				
				// The formula is denoted by a blank node, unless we set
				// the override meta flag above.
				if (context.overrideMeta == null)
					newcontext.meta = new BNode();
				else
					newcontext.meta = context.overrideMeta;
				
				// According to the spec, _:xxx anonymous nodes are
				// local to the formula.  But ?$variables (which aren't
				// mentioned in the spec) are treated as global names.
				newcontext.anonymous = new Hashtable();
				
				while (NextPunc(context.source) != '}' && ReadStatement(newcontext)) { }
				ReadWhitespace(context.source);
				if (context.source.Peek() == '}') context.source.Read();
				
				return newcontext.meta;
			}
			
			// NUMERIC LITERAL
			
			// In Turtle, numbers are restricted to [0-9]+, and are datatyped xsd:integer.
			double numval;
			#if !SILVERLIGHT
			if (double.TryParse(str, System.Globalization.NumberStyles.Any, null, out numval)) {
			#else
			bool ok = true;
			numval = 0;
			try {
				numval = double.Parse(str);
			} catch (Exception) {
				ok = false;
			}
			if (ok) {
			#endif
				if (numval >= long.MinValue && numval <= long.MaxValue && numval == (double)(long)numval)
					return new Literal(((long)numval).ToString(), null, NS.XMLSCHEMA + "integer");
				else
					return new Literal(numval.ToString(), null, NS.XMLSCHEMA + "double");
			}
			
			//BOOLEAN LITERAL
			
			if (str == "true" || str == "false") {
			  return new Literal(str,null,NS.XMLSCHEMA+"boolean");
			}
			
			// If @keywords is used, alphanumerics that aren't keywords
			// are local names in the default namespace.
			if (context.UsingKeywords && char.IsLetter(str[0])) {
				if (BaseUri == null)
					OnError("The document contains an unqualified name but no BaseUri was specified: \"" + str + "\"", loc);
				return GetResource(context, BaseUri + str);
			}
			
			// NOTHING MATCHED
			
			OnError("Invalid token: " + str, loc);
			return null;
		}
		
		private void Add(StatementSink store, Statement statement, Location position) {
			store.Add(statement);
		}
示例#34
0
        public void TestFormulaWithList()
        {
            N3Writer instance = (N3Writer)CreateInstance();

            BNode listId = new BNode();
            BNode listTwoId = new BNode();
            BNode listThreeId = new BNode();
            instance.Add(new Statement(listId, Predicate.RdfFirst, (Entity)"A"));
            instance.Add(new Statement(listId, Predicate.RdfRest, listTwoId));
            instance.Add(new Statement(listTwoId, Predicate.RdfFirst, (Entity)"B"));
            instance.Add(new Statement(listTwoId, Predicate.RdfRest, listThreeId));
            instance.Add(new Statement(listThreeId, Predicate.RdfFirst, (Entity)"C"));
            instance.Add(new Statement(listThreeId, Predicate.RdfRest, Identifier.RdfNil));

            BNode statementXId = new BNode();
            BNode statementYId = new BNode();
            instance.Add(new Statement(listId, "p", (Entity)"X", statementXId));
            instance.Add(new Statement(listId, "p", (Entity)"Y", statementYId));
            instance.Add(new Statement(statementXId, Predicate.LogImplies, statementYId));
            instance.Close();

            string expected = "{(<A> <B> <C>) <p> <X>.} => {(<A> <B> <C>) <p> <Y>.}.";
            Assert.AreEqual(expected, writer.ToString());
        }
示例#35
0
        private Entity ParseDescription()
        {
            // The XmlReader is positioned on an element node
            // that is a description of an entity.
            // On returning, the reader is positioned after the
            // end element of the description node.

            string nodeID = xml.GetAttribute("nodeID", NS.RDF);
            string about  = xml.GetAttribute("about", NS.RDF);
            string ID     = xml.GetAttribute("ID", NS.RDF);

            if (isset(nodeID) + isset(about) + isset(ID) > 1)
            {
                OnError("An entity description cannot specify more than one of rdf:nodeID, rdf:about, and rdf:ID");
            }

            if (nodeID != null && !IsValidXmlName(nodeID))
            {
                OnWarning("'" + nodeID + "' is not a valid XML Name");
            }
            if (ID != null && !IsValidXmlName(ID))
            {
                OnWarning("'" + ID + "' is not a valid XML Name");
            }

            Entity entity;

            if (about != null)
            {
                entity = GetNamedNode(Unrelativize(about));
            }
            else if (ID != null)
            {
                entity = GetNamedNode(Unrelativize("#" + ID));

                if (seenIDs.ContainsKey(entity.Uri))
                {
                    OnWarning("Two descriptions should not use the same rdf:ID: <" + entity.Uri + ">");
                }
                seenIDs[entity.Uri] = seenIDs;
            }
            else if (nodeID != null)
            {
                entity = GetBlankNode(nodeID);
            }
            else
            {
                entity = new BNode();
            }

            // If the name of the element is not rdf:Description,
            // then the name gives its type.
            string curnode = CurNode();

            if (curnode != NS.RDF + "Description")
            {
                if (IsRestrictedName(curnode) || IsDeprecatedName(curnode))
                {
                    OnError(xml.Name + " cannot be the type of a resource");
                }
                if (curnode == NS.RDF + "li")
                {
                    OnError("rdf:li cannot be the type of a resource");
                }
                storage.Add(new Statement(entity, rdfType, (Entity)curnode, Meta));
            }

            ParsePropertyAttributes(entity);
            ParsePropertyNodes(entity);

            return(entity);
        }
示例#36
0
        /// <summary>
        /// Adds the statement of a formula.
        /// </summary>
        /// <param name="statement">The statement.</param>
        protected virtual void AddFormulaStatement(Statement statement)
        {
            Entity formulaId = statement.Meta;
            Entity statementId = new BNode();

            if (m_LastFormulaId != formulaId)
            {
                m_LastFormulaId = formulaId;
                AddStatement(new Statement(formulaId, Predicate.RdfType, Identifier.LogFormula));
            }

            AddStatement(new Statement(formulaId, Predicate.LogIncludes, statementId));
            AddStatement(new Statement(statementId, Predicate.RdfType, Identifier.RdfStatement));
            AddStatement(new Statement(statementId, Predicate.RdfSubject, statement.Subject));
            AddStatement(new Statement(statementId, Predicate.RdfPredicate, statement.Predicate));
            AddStatement(new Statement(statementId, Predicate.RdfObject, statement.Object));
        }
示例#37
0
        private Resource ReadResource2(ParseContext context, bool allowDirective, out bool reverse, out bool forgetBNode)
        {
            reverse     = false;
            forgetBNode = false;

            Location loc = context.Location;

            object tok = ReadToken(context.source, context);

            if (tok is Literal)
            {
                return((Literal)tok);
            }

            string str = (string)tok;

            if (str == "")
            {
                return(null);
            }

            // Directives

            if (str == "@prefix")
            {
                if (allowDirective)
                {
                    return(PrefixResource);
                }
                else
                {
                    OnError("The directive '" + str + "' is not allowed here", loc);
                }
            }

            if (str == "@keywords")
            {
                if (allowDirective)
                {
                    return(KeywordsResource);
                }
                else
                {
                    OnError("The directive '" + str + "' is not allowed here", loc);
                }
            }

            if (str == "@base")
            {
                if (allowDirective)
                {
                    return(BaseResource);
                }
                else
                {
                    OnError("The directive '" + str + "' is not allowed here", loc);
                }
            }

            // @ Keywords

            if (context.UsingKeywords && context.Keywords.Contains(str))
            {
                str = "@" + str;
            }
            if (!context.UsingKeywords &&
                (str == "a" || str == "has" || str == "is"))
            {
                str = "@" + str;
            }

            // Standard Keywords
            // TODO: Turn these off with @keywords

            if (str == "@a")
            {
                return(entRDFTYPE);
            }

            if (str == "=")
            {
                return(entDAMLEQUIV);
            }
            if (str == "=>")
            {
                return(entLOGIMPLIES);
            }
            if (str == "<=")
            {
                reverse = true;
                return(entLOGIMPLIES);
            }
            if (str == "=:>")             // SPECIAL EXTENSION!
            {
                return(entGRAPHCONTAINS);
            }

            if (str == "@has")             // ignore this token
            {
                return(ReadResource2(context, false, out reverse, out forgetBNode));
            }

            if (str == "@is")
            {
                // Reverse predicate
                bool     reversetemp;
                Resource pred = ReadResource2(context, false, out reversetemp, out forgetBNode);
                reverse = true;

                string of = ReadToken(context.source, context) as string;
                if (of == null)
                {
                    OnError("End of stream while expecting 'of'", loc);
                }
                if (of == "@of" ||
                    (!context.UsingKeywords && of == "of") ||
                    (context.UsingKeywords && context.Keywords.Contains("of") && of == "of"))
                {
                    return(pred);
                }
                OnError("Expecting token 'of' but found '" + of + "'", loc);
                return(null);                // unreachable
            }

            if (str.StartsWith("@"))
            {
                OnError("The " + str + " directive is not supported", loc);
            }

            // URI

            if (str.StartsWith("<") && str.EndsWith(">"))
            {
                string uri      = GetAbsoluteUri(BaseUri, str.Substring(1, str.Length - 2));
                string urierror = Entity.ValidateUri(uri);
                if (urierror != null)
                {
                    OnWarning(urierror, loc);
                }
                return(GetResource(context, uri));
            }

            // VARIABLE

            if (str[0] == '?')
            {
                string name = str.Substring(1);
                Entity varb = (Entity)context.variables[name];
                if (varb == null)
                {
                    varb = new Variable(name);
                    AddVariable((Variable)varb);
                    context.variables[name] = varb;
                }
                return(varb);
            }

            // QNAME

            if (str.IndexOf(":") != -1)
            {
                return(ResolveQName(str, context, loc));
            }

            // ANONYMOUS

            if (str == "[")
            {
                Entity ret = new BNode();
                ReadWhitespace(context.source);
                if (context.source.Peek() != ']')
                {
                    char bracket = ReadPredicates(ret, context);
                    if (bracket == '.')
                    {
                        bracket = ReadPunc(context.source);
                    }
                    if (bracket != ']')
                    {
                        OnError("Expected a close bracket but found '" + bracket + "'", loc);
                    }
                }
                else
                {
                    context.source.Read();
                }
                forgetBNode = true;
                return(ret);
            }

            // LIST

            if (str == "(")
            {
                // A list
                Entity head = null, ent = null;
                while (true)
                {
                    bool     rev2, fb2;
                    Resource res = ReadResource(context, false, out rev2, out fb2);
                    if (res == null)
                    {
                        break;
                    }

                    if (ent == null)
                    {
                        ent  = new BNode();
                        head = ent;
                    }
                    else
                    {
                        Entity sub = new BNode();
                        Add(context.store, new Statement(ent, entRDFREST, sub, context.meta), loc);
                        ent = sub;
                    }

                    Add(context.store, new Statement(ent, entRDFFIRST, res, context.meta), loc);
                    if (fb2)
                    {
                        DoForget(res, context);
                    }
                }
                if (head == null)                 // No list items.
                {
                    head = entRDFNIL;             // according to Turtle spec
                }
                else
                {
                    Add(context.store, new Statement(ent, entRDFREST, entRDFNIL, context.meta), loc);
                }

                return(head);
            }

            if (str == ")")
            {
                return(null);                // Should I use a more precise end-of-list return value?
            }
            // FORMULA

            if (str == "{")
            {
                // ParseContext is a struct, so this gives us a clone.
                ParseContext newcontext = context;

                // The formula is denoted by a blank node, unless we set
                // the override meta flag above.
                if (context.overrideMeta == null)
                {
                    newcontext.meta = new BNode();
                }
                else
                {
                    newcontext.meta = context.overrideMeta;
                }

                // According to the spec, _:xxx anonymous nodes are
                // local to the formula.  But ?$variables (which aren't
                // mentioned in the spec) are treated as global names.
                newcontext.anonymous = new Hashtable();

                while (NextPunc(context.source) != '}' && ReadStatement(newcontext))
                {
                }
                ReadWhitespace(context.source);
                if (context.source.Peek() == '}')
                {
                    context.source.Read();
                }

                return(newcontext.meta);
            }

            // NUMERIC LITERAL

            // In Turtle, numbers are restricted to [0-9]+, and are datatyped xsd:integer.
            double numval;

                        #if !SILVERLIGHT
            if (double.TryParse(str, System.Globalization.NumberStyles.Any, null, out numval))
            {
                        #else
            bool ok = true;
            numval = 0;
            try {
                numval = double.Parse(str);
            }
            catch (Exception) {
                ok = false;
            }
            if (ok)
            {
                        #endif
                if (numval >= long.MinValue && numval <= long.MaxValue && numval == (double)(long)numval)
                {
                    return(new Literal(((long)numval).ToString(), null, NS.XMLSCHEMA + "integer"));
                }
                else
                {
                    return(new Literal(numval.ToString(), null, NS.XMLSCHEMA + "double"));
                }
            }

            //BOOLEAN LITERAL

            if (str == "true" || str == "false")
            {
                return(new Literal(str, null, NS.XMLSCHEMA + "boolean"));
            }

            // If @keywords is used, alphanumerics that aren't keywords
            // are local names in the default namespace.
            if (context.UsingKeywords && char.IsLetter(str[0]))
            {
                if (BaseUri == null)
                {
                    OnError("The document contains an unqualified name but no BaseUri was specified: \"" + str + "\"", loc);
                }
                return(GetResource(context, BaseUri + str));
            }

            // NOTHING MATCHED

            OnError("Invalid token: " + str, loc);
            return(null);
        }