Example #1
0
		private string Literal(Literal literal) {
			#if !SILVERLIGHT
			if (format == Formats.NTriples || literal.DataType == null) return literal.ToString();
			if (literal.DataType == xsdInteger) return literal.ParseValue().ToString();
			if (literal.DataType == xsdDouble && format == Formats.Notation3) return literal.ParseValue().ToString();
			#endif
			return literal.ToString();
		}
        private static string GetTextField(Resource value)
        {
            string text_field = null;

            SemWeb.Literal l = value as SemWeb.Literal;
            if (l != null && l.Value != null && l.Value.Length > 0)
            {
                text_field = l.Value;
                if (Char.IsControl(l.Value [l.Value.Length - 1]))
                {
                    text_field = l.Value.Substring(0, l.Value.Length - 1);
                }
            }
            return(text_field);
        }
Example #3
0
        public virtual string GetValue(MemoryStore store, SemWeb.Literal obj)
        {
            string result = obj.Value;

            if (type.IsEnum)
            {
                try {
                    object o = System.Enum.Parse(type, obj.Value);
                    result = o.ToString();
                } catch (System.Exception e) {
                    System.Console.WriteLine("Value \"{2}\" not found in {0}{3}{1}", type, e, result, System.Environment.NewLine);
                }
            }

            /*
             * else if (type == typeof (Rational)) {
             *      object o = FSpot.Tiff.Rational.Parse (obj.Value);
             * }
             */
            return(result);
        }
			public LiteralWrapper(Literal res) { r = res; }
			protected override void extractLiteralFilters(name.levering.ryan.sparql.model.logic.ExpressionLogic node, java.util.Map literalFilters) {
				base.extractLiteralFilters(node, literalFilters);
			
				if (node is BinaryExpressionNode) {
					BinaryExpressionNode b = (BinaryExpressionNode)node;
					
					LiteralFilter.CompType comp;
					if (node is ASTEqualsNode)
						comp = LiteralFilter.CompType.EQ;
					else if (node is ASTNotEqualsNode)
						comp = LiteralFilter.CompType.NE;
					else if (node is ASTGreaterThanNode)
						comp = LiteralFilter.CompType.GT;
					else if (node is ASTGreaterThanEqualsNode)
						comp = LiteralFilter.CompType.GE;
					else if (node is ASTLessThanNode)
						comp = LiteralFilter.CompType.LT;
					else if (node is ASTLessThanEqualsNode)
						comp = LiteralFilter.CompType.LE;
					else
						return;
					
					SparqlVariable var;
					org.openrdf.model.Literal val;
					
					object left = RemoveCast(b.getLeftExpression());
					object right = RemoveCast(b.getRightExpression());
					
					if (left is ASTVar && right is org.openrdf.model.Literal) {
						var = (SparqlVariable)left;
						val = (org.openrdf.model.Literal)right;
					} else if (right is ASTVar && left is org.openrdf.model.Literal) {
						var = (SparqlVariable)right;
						val = (org.openrdf.model.Literal)left;
						switch (comp) {
						case LiteralFilter.CompType.LT: comp = LiteralFilter.CompType.GE; break;
						case LiteralFilter.CompType.LE: comp = LiteralFilter.CompType.GT; break;
						case LiteralFilter.CompType.GT: comp = LiteralFilter.CompType.LE; break;
						case LiteralFilter.CompType.GE: comp = LiteralFilter.CompType.LT; break;
						}
					} else {
						return;
					}
					
					object parsedvalue = new Literal(val.getLabel(), null, val.getDatatype() == null ? null : val.getDatatype().ToString()).ParseValue();
					
					LiteralFilter filter = LiteralFilter.Create(comp, parsedvalue);
					addLiteralFilter(var, filter, literalFilters);
				}
			}
Example #6
0
		public abstract bool Filter(Literal value, SelectableSource targetModel);
Example #7
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));
            }
        }
Example #8
0
 protected object GetObject(Literal lit)
 {
     //TDB
     return lit.Value;
 }
Example #9
0
 protected void ValidateLiteral(Literal literal)
 {
     #if !SILVERLIGHT
     if (!validateLiterals) return;
     try {
         literal.ParseValue();
     } catch (FormatException e) {
         OnWarning("Typed literal has an invalid lexical value: " + e.Message + ": " + literal);
     } catch (ArgumentOutOfRangeException e) {
         OnWarning("Typed literal has an invalid lexical value: " + literal);
     }
     #endif
 }
Example #10
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);
        }
Example #11
0
 public LiteralWrapper(Literal res)
 {
     r = res; hc = java.lang.String.instancehelper_hashCode(r.Value);
 }
		public StringContainsFilter(Literal res) : base(res) { }
		public NumericFilter(Literal res) : this(int.Parse(res.Value)) { }
		// Specify:
		//   compareResult  orEqual  Meaning
		//        -1         false   Less Than
		//        -1         true    Less Than Or Equal
		//         0         false   Not Equal
		//         0         true    Equal
		//         1         false   Greater Than
		//         1         true    Greater Than Or Equal
		
		public StringCompareFilter(Literal res, int compareResult, bool orEqual) : base(res) { compare = compareResult; eq = orEqual; }
		public StringFilter(Literal res) : this(res.Value) {
		}
		public TimeSpanFilter(Literal res) : this(TimeSpan.Parse(res.Value)) { }
		public DateTimeFilter(Literal res) : this(DateTime.Parse(res.Value)) { }
		private static void ProcessResponse(string mimetype, Stream stream, object outputObj) {
		
			// If the user wants the output sent to a TextWriter, copy the response from
			// the response stream to the TextWriter. TODO: Get encoding from HTTP header.
			if (outputObj is TextWriter) {
				TextWriter tw = (TextWriter)outputObj;
				using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8)) {
					char[] buffer = new char[512];
					while (true) {
						int len = reader.Read(buffer, 0, buffer.Length);
						if (len <= 0) break;
						tw.Write(buffer, 0, len);
						
						if (Debug) {
							Console.Error.WriteLine(">> " + new String(buffer, 0, len));
						}
					}
				}
				tw.Flush();
				return;
			}
			
			// If the user wants a boolean out of this, then we're expecting a
			// SPARQL XML Results document with a boolean response element.
			if (outputObj is BooleanWrap) {
				BooleanWrap bw = (BooleanWrap)outputObj;
				
				if (mimetype != null && mimetype != "application/sparql-results+xml" && mimetype != "text/xml" && mimetype != "application/xml")
					throw new ApplicationException("The result of the query was not a SPARQL Results document.");
					
				XmlReader xmldoc = new XmlTextReader(stream);
				{
					// Move to the document element
					while (xmldoc.Read())
						if (xmldoc.NodeType == XmlNodeType.Element) break;
						
					// Just check that it has the right local name.
					if (xmldoc.LocalName != "sparql" || xmldoc.IsEmptyElement)
						throw new ApplicationException("Invalid server response: Not a SPARQL results document.");
								
					// Move to the next node.
					while (xmldoc.Read())
						if (xmldoc.NodeType == XmlNodeType.Element) break;
						
					// If it's a head node, skip it.
					if (xmldoc.LocalName == "head") {
						xmldoc.Skip();
						// Move to the 'boolean' element, it better be next
						while (xmldoc.Read())
							if (xmldoc.NodeType == XmlNodeType.Element) break;
					}
						
					if (xmldoc.LocalName != "boolean")
						throw new ApplicationException("Invalid server response: Missing 'boolean' element.");
					
					string value = xmldoc.ReadElementString();
					bw.value = (value == "true");
				}
						
				if (Debug) {
					Console.Error.WriteLine(">> " + bw.value);
				}
				
				return;
			}
			
			// If the user wants statements out of the response, read it with an RDFReader.
			if (outputObj is StatementSink) {
				// If the mime type is application/sparql-results+xml, just try to
				// read it as if it were an RDF/XML MIME type.
				if (mimetype != null && mimetype == "application/sparql-results+xml") mimetype = "text/xml";
				using (RdfReader reader = RdfReader.Create(mimetype, stream))
					reader.Select((StatementSink)outputObj);
				if (Debug) {
					Console.Error.WriteLine(">> (read as statements)");
				}
				return;
			}
			
			// If the user wants query result bindings, read the response XML.
			if (outputObj is QueryResultSink) {
				QueryResultSink sink = (QueryResultSink)outputObj;
			
				if (mimetype != null && mimetype != "application/sparql-results+xml" && mimetype != "text/xml")
					throw new ApplicationException("The result of the query was not a SPARQL Results document.");
					
				ArrayList variableNames = new ArrayList();
				ArrayList variables = new ArrayList();
				Variable[] variablesArray = null;
				Hashtable bnodes = new Hashtable();

				XmlReader xmldoc = new XmlTextReader(stream);
				{
					// Move to the document element
					while (xmldoc.Read())
						if (xmldoc.NodeType == XmlNodeType.Element) break;
						
					// Just check that it has the right local name.
					if (xmldoc.LocalName != "sparql" || xmldoc.IsEmptyElement)
						throw new ApplicationException("Invalid server response: Not a SPARQL results document.");
								
					// Move to the 'head' node, it better be the first element
					while (xmldoc.Read())
						if (xmldoc.NodeType == XmlNodeType.Element) break;
						
					if (xmldoc.LocalName != "head" || xmldoc.IsEmptyElement)
						throw new ApplicationException("Invalid server response: Missing head full element.");
						
					// Read the head element
					while (xmldoc.Read()) {
						if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "variable") {
							if (xmldoc.GetAttribute("name") == null)
								throw new ApplicationException("Invalid server response: Head/variable node missing name attribute.");
							variableNames.Add(xmldoc.GetAttribute("name"));
							variables.Add(new Variable(xmldoc.GetAttribute("name")));
							if (!xmldoc.IsEmptyElement) xmldoc.Skip();
						} else if (xmldoc.NodeType == XmlNodeType.EndElement) {
							break;
						}
					}
					
					// Move to the 'results' element, it better be next
					while (xmldoc.Read())
						if (xmldoc.NodeType == XmlNodeType.Element) break;
						
					if (xmldoc.LocalName != "results")
						throw new ApplicationException("Invalid server response: Missing results element.");
					
					variablesArray = (Variable[])variables.ToArray(typeof(Variable));
					sink.Init(variablesArray);
					
					// Read the results
					
					while (xmldoc.Read()) {
						if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "result") {
							// Read the bindings in this result
							Resource[] valuesArray = new Resource[variablesArray.Length];
							while (xmldoc.Read()) {
								if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "binding") {
									if (xmldoc.IsEmptyElement)
										throw new ApplicationException("Invalid server response: Binding element empty.");
									if (xmldoc.GetAttribute("name") == null)
										throw new ApplicationException("Invalid server response: Result binding node missing name attribute.");
									int vIndex = variableNames.IndexOf(xmldoc.GetAttribute("name"));
									if (vIndex == -1)
										throw new ApplicationException("Invalid server response: Result binding name does not match a variable in the head.");
									
									Resource value = null;
									
									while (xmldoc.Read()) {
										if (xmldoc.NodeType == XmlNodeType.Whitespace || xmldoc.NodeType == XmlNodeType.SignificantWhitespace) continue;
										if (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "uri") {
											value = new Entity(xmldoc.ReadElementString());
											if (!xmldoc.IsEmptyElement) xmldoc.Skip();
										} else if  (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "literal") {
											string lang = xmldoc.XmlLang;
											if (lang == "") lang = null;
											string dt = xmldoc.GetAttribute("datatype");
											value = new Literal(xmldoc.ReadElementString(), lang, dt);
											if (!xmldoc.IsEmptyElement) xmldoc.Skip();
										} else if  (xmldoc.NodeType == XmlNodeType.Element && xmldoc.LocalName == "bnode") {
											string id = xmldoc.ReadElementString();
											if (bnodes.ContainsKey(id)) {
												value = (BNode)bnodes[id];
											} else {
												value = new BNode(id);
												bnodes[id] = value;
											}
											if (!xmldoc.IsEmptyElement) xmldoc.Skip();
										} else {
											throw new ApplicationException("Invalid server response: Invalid content in binding node.");
										}
										break;
									}
									if (value == null)
										throw new ApplicationException("Invalid server response: Result binding value is invalid.");
									
									valuesArray[vIndex] = value;

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

					sink.Finished();
				}
			}
		}
Example #19
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));
			}
		}
        public void ProcessStore(MetadataStore store, Photo photo)
        {
            Hashtable descriptions = new Hashtable();
            uint      rating       = System.UInt32.MaxValue;
            uint      urgency      = System.UInt32.MaxValue;

            foreach (Statement stmt in store)
            {
                //StatementList list = null;

                switch (stmt.Predicate.Uri)
                {
                case Caption:
                case Headline:
                    if (!descriptions.Contains(stmt.Predicate.Uri))
                    {
                        string caption = GetTextField(stmt.Object as SemWeb.Literal);
                        if (caption != null)
                        {
                            caption = caption.Trim();
                        }

                        if ((caption != null) && (caption.Length > 0))
                        {
                            descriptions.Add(stmt.Predicate.Uri, caption);
                        }
                    }
                    break;

                case Title:
                case Description:
                case UserComment:
                    if (!(stmt.Object is Entity))
                    {
                        break;
                    }

                    foreach (Statement tag in store.Select(new Statement(stmt.Object as Entity, null, null)))
                    {
                        if ((tag.Predicate != RdfType) && (!descriptions.Contains(stmt.Predicate.Uri)))
                        {
                            string title = null;
                            try {
                                title = (GetTextField((SemWeb.Literal)tag.Object)).Trim();
                            } catch {
                            }
                            if ((title != null) && (title.Length > 0))
                            {
                                descriptions.Add(stmt.Predicate.Uri, title);
                            }
                        }
                    }
                    break;

                case Urgency:                 // Used if Rating was not found
                case Rating:
                    SemWeb.Literal l = stmt.Object as SemWeb.Literal;
                    if (l != null && l.Value != null && l.Value.Length > 0)
                    {
                        uint tmp_ui;
                        try {
                            tmp_ui = System.Convert.ToUInt32(l.Value);
                        } catch {
                            // Set rating to 0, and continue
                            Log.DebugFormat("Found illegal rating >{0}< in predicate {1}. Rating cleared",
                                            l.Value, stmt.Predicate.Uri);
                            tmp_ui = 0;
                        }
                        if (tmp_ui > 5)                         // Max rating allowed in F-Spot
                        {
                            tmp_ui = 5;
                        }
                        if (stmt.Predicate.Uri == Rating)
                        {
                            rating = tmp_ui;
                        }
                        else
                        {
                            urgency = tmp_ui == 0 ? 0 : tmp_ui - 1;                             // Urgency valid values 1 - 8
                        }
                    }
                    break;

                case State:
                case City:
                case Country:
                case Location:
                case Source:
                    AddTagToPhoto(photo, stmt.Object as SemWeb.Literal, taginfo_table [stmt.Predicate] as TagInfo);
                    break;

                case Subject:
                case SupplementalCategories:
                case People:
                    if (!(stmt.Object is Entity))
                    {
                        break;
                    }

                    foreach (Statement tag in store.Select(new Statement(stmt.Object as Entity, null, null)))
                    {
                        if (tag.Predicate != RdfType)
                        {
                            AddTagToPhoto(photo, tag.Object as SemWeb.Literal, null);
                        }
                    }
                    break;
                }
            }

            if (descriptions.Contains(UserComment))
            {
                photo.Description = descriptions [UserComment] as String;
            }

            // Use the old urgency, only if rating was not available.
            if (urgency < System.UInt32.MaxValue)
            {
                photo.Rating = urgency;
            }
            if (rating < System.UInt32.MaxValue)
            {
                photo.Rating = rating;
            }

#if false
            //FIXME: looks like we are doing some questionable repurposing of tags here...

            // We want to construct the following : Description = <Headline> :: <Caption>

            // only check for more title/comment if you still do not have one.
            if ((photo.Description == null) || (photo.Description.Length == 0))
            {
                if (descriptions.Contains(Headline))
                {
                    photo.Description = descriptions [Headline] as String;
                }
                // Lets add the Caption to the existing Description (Headline).
                if (descriptions.Contains(Caption))
                {
                    photo.Description += (((photo.Description == null) ? "" : " :: ") + descriptions [Caption] as String);
                }
            }

            // only check for more title/comment if you still do not have one.
            if ((photo.Description == null) || (photo.Description.Length == 0))
            {
                if (descriptions.Contains(Title))
                {
                    photo.Description = descriptions [Title] as String;
                }
                // Lets add the Description  to the existing Description (Title).
                if (descriptions.Contains(Description))
                {
                    photo.Description += (((photo.Description == null) ? "" : " :: ") + descriptions [Description] as String);
                }
            }
#endif
        }
Example #21
0
            protected override void extractLiteralFilters(name.levering.ryan.sparql.model.logic.ExpressionLogic node, java.util.Map literalFilters)
            {
                //Console.Error.WriteLine(node + " " + node.GetType());
                base.extractLiteralFilters(node, literalFilters);

                if (node is BinaryExpressionNode) {
                    BinaryExpressionNode b = (BinaryExpressionNode)node;

                    LiteralFilter.CompType comp;
                    if (node is ASTEqualsNode)
                        comp = LiteralFilter.CompType.EQ;
                    else if (node is ASTNotEqualsNode)
                        comp = LiteralFilter.CompType.NE;
                    else if (node is ASTGreaterThanNode)
                        comp = LiteralFilter.CompType.GT;
                    else if (node is ASTGreaterThanEqualsNode)
                        comp = LiteralFilter.CompType.GE;
                    else if (node is ASTLessThanNode)
                        comp = LiteralFilter.CompType.LT;
                    else if (node is ASTLessThanEqualsNode)
                        comp = LiteralFilter.CompType.LE;
                    else
                        return;

                    SparqlVariable var;
                    name.levering.ryan.sparql.common.Literal val;

                    object left = RemoveCast(b.getLeftExpression());
                    object right = RemoveCast(b.getRightExpression());

                    if (left is ASTVar && right is name.levering.ryan.sparql.common.Literal) {
                        var = (SparqlVariable)left;
                        val = (name.levering.ryan.sparql.common.Literal)right;
                    } else if (right is ASTVar && left is name.levering.ryan.sparql.common.Literal) {
                        var = (SparqlVariable)right;
                        val = (name.levering.ryan.sparql.common.Literal)left;
                        switch (comp) {
                        case LiteralFilter.CompType.LT: comp = LiteralFilter.CompType.GE; break;
                        case LiteralFilter.CompType.LE: comp = LiteralFilter.CompType.GT; break;
                        case LiteralFilter.CompType.GT: comp = LiteralFilter.CompType.LE; break;
                        case LiteralFilter.CompType.GE: comp = LiteralFilter.CompType.LT; break;
                        }
                    } else {
                        return;
                    }

                    object parsedvalue = new Literal(val.getLabel(), null, val.getDatatype() == null ? null : val.getDatatype().getURI()).ParseValue();

                    LiteralFilter filter = LiteralFilter.Create(comp, parsedvalue);
                    addLiteralFilter(var, filter, literalFilters);

                } else if (node is ASTRegexFuncNode) {
                    ASTRegexFuncNode renode = (ASTRegexFuncNode)node;

                    SparqlVariable var = RemoveCast(renode.getArguments().get(0)) as ASTVar;
                    name.levering.ryan.sparql.common.Literal relit = RemoveCast(renode.getArguments().get(1)) as name.levering.ryan.sparql.common.Literal;

                    if (var == null || relit == null) return;

                    string re = relit.getLabel();
                    if (re.Length == 0) return;

                    bool startsW = removeChar(ref re, '^', 0); // chop of ^ from start, return whether it was there
                    bool endsW = removeChar(ref re, '$', 1); // chop of $ from end, return whether it was there

                    // make sure the re that's left has no special re characters
                    foreach (char c in re)
                        if (c == '(' || c == '[' || c == '{' || c == '*' || c == '?' || c == '+' || c == '\\' || c == '|' || c == '.')
                            return;

                    LiteralFilter filter;
                    if (startsW && endsW) {
                        filter = LiteralFilter.Create(LiteralFilter.CompType.EQ, re);
                    } else if (startsW) {
                        filter = new SemWeb.Filters.StringStartsWithFilter(re);
                    } else if (endsW) {
                        filter = new SemWeb.Filters.StringEndsWithFilter(re);
                    } else {
                        filter = new SemWeb.Filters.StringContainsFilter(re);
                    }
                    addLiteralFilter(var, filter, literalFilters);
                }
            }
Example #22
0
		private object ReadToken(MyReader source, ParseContext context) {
			ReadWhitespace(source);
			
			Location loc = new Location(source.Line, source.Col);
			
			int firstchar = source.Read();
			if (firstchar == -1)
				return "";
			
			StringBuilder b = readTokenBuffer; readTokenBuffer.Length = 0;
			b.Append((char)firstchar);

			if (firstchar == '<') {
				// This is a URI or the <= verb.  URIs can have \'s and <'s escaped with a backslash, plus \u and \U notation.
				bool escaped = false;
				while (true) {
					int c = source.Read();
					if (c == -1) OnError("Unexpected end of stream within a token beginning with <", loc);
					
					if (b.Length == 2 && c == '=')
						return "<="; // the <= verb
					
					if (escaped) {
						ReadEscapedChar((char)c, b, source, loc, true, true, false);
							// the first flag should be set true only if not NTriples, but we are flexible on reading.
							// the second flag should be set true only if NTriples, but we are flexible on reading.
						escaped = false;
					} else if (c == '\\') {
						escaped = true;
					} else {
						b.Append((char)c);
						if (c == '>') // end of the URI
							break;
					}
				}
				
			} else if (firstchar == '"') {
				// This can either be a string "..." or a longString """...""", which additionally allows embedded \n, \r, and \t, and quotes.
				
				b.Length = 0; // get rid of the open quote
				bool escaped = false;
				bool triplequoted = false;
				while (true) {
					int c = source.Read();
					if (c == -1) OnError("Unexpected end of stream within a string", loc);
					
					// Check if this is started by three quotes. If we've already read three quotes, don't keep checking or we can't read """""".
					if (b.Length == 0 && c == (int)'"' && source.Peek() == (int)'"' && !triplequoted) {
						triplequoted = true;
						source.Read();
						continue;
					}
					
					if (escaped) {
						ReadEscapedChar((char)c, b, source, loc, false, true, true); // the last flag should be set true only if N3, but we are flexible on reading
						escaped = false;
					} else if (c == '\\') {
						escaped = true;
					} else {
						if (c == '"' && !triplequoted)
							break;
						if (c == '"' && source.Peek() == '"' && source.Peek2() == '"' && triplequoted)
							break;
						b.Append((char)c);
					}
				}
				
				if (triplequoted) { // read the extra end quotes
					source.Read();
					source.Read();
				}
				
				string litvalue = b.ToString();
				string litlang = null;
				string litdt = null;

				// Strings can be suffixed with @langcode or ^^symbol (but not both?).
				if (source.Peek() == '@') {
					source.Read();
					b.Length = 0;
					while (char.IsLetterOrDigit((char)source.Peek()) || source.Peek() == (int)'-')
						b.Append((char)source.Read());
					litlang = b.ToString();
				} else if (source.Peek() == '^' && source.Peek2() == '^') {
					loc = new Location(source.Line, source.Col);
					source.Read();
					source.Read();
					litdt = ReadToken(source, context).ToString(); // better be a string URI
					if (litdt.StartsWith("<") && litdt.EndsWith(">"))
						litdt = litdt.Substring(1, litdt.Length-2);
					else if (litdt.IndexOf(":") != -1) {
						Resource r = ResolveQName(litdt, context, loc);
						if (r.Uri == null)
							OnError("A literal datatype cannot be an anonymous entity", loc);
						litdt = r.Uri;
					}
				}
				
				Literal literal = new Literal(litvalue, litlang, litdt);
				ValidateLiteral(literal);
				return literal;

			} else if (char.IsLetter((char)firstchar) || firstchar == '?' || firstchar == '@' || firstchar == ':' || firstchar == '_') {
				// Something starting with @
				// A QName: ([a-zA-Z_][a-zA-Z0-9_]*)?:)?([a-zA-Z_][a-zA-Z0-9_]*)?
				// A variable: \?[a-zA-Z_][a-zA-Z0-9_]*
				while (true) {
					int c = source.Peek();
					if (c == -1 || (!Entity.ValidateUriIsIUnreserved((char)c) && c != ':') || c == '.') break;
					b.Append((char)source.Read());
				}
			
			} else if (char.IsDigit((char)firstchar) || firstchar == '+' || firstchar == '-') {
				while (true) {
					int ci = source.Peek();
					if (ci == -1) break;
					if (ci == ']' || ci == ')' || ci == '}') break;
					
					// punctuation followed by a space means the punctuation is
					// punctuation, and not part of this token
					if (!char.IsDigit((char)ci) && source.Peek2() != -1 && char.IsWhiteSpace((char)source.Peek2()))
						break;
					
					char c = (char)ci;
					if (char.IsWhiteSpace(c)) break;
					
					b.Append((char)source.Read());
				}
				
			} else if (firstchar == '=') {
				if (source.Peek() == (int)'>')
					b.Append((char)source.Read());
				
				if (source.Peek() == (int)':' && source.Peek2() == (int)'>') { // SPECIAL EXTENSION "=:>"
					b.Append((char)source.Read());
					b.Append((char)source.Read());
				}
			
			} else if (firstchar == '[') {
				// The start of an anonymous node.

			} else if (firstchar == '{') {
				return "{";

			} else if (firstchar == '(') {
				return "(";
			} else if (firstchar == ')') {
				return ")";

			} else {
				while (true) {
					int c = source.Read();
					if (c == -1) break;
					if (char.IsWhiteSpace((char)c)) break;
					b.Append((char)c);
				}
				OnError("Invalid token: " + b.ToString(), loc);
			}
			
			return b.ToString();
		}
 /// <summary>
 /// Writes the literal to the output writer.
 /// </summary>
 /// <param name="literal">The literal.</param>
 protected virtual void WriteLiteral(Literal literal)
 {
     if(!String.IsNullOrEmpty(literal.Language))
     {
         WriteLiteralValueWithLanguage(literal.Value, literal.Language);
     }
     else if(!String.IsNullOrEmpty(literal.DataType))
     {
         WriteLiteralValueWithDataType(literal.Value, literal.DataType);
     }
     else
     {
         WriteLiteralValue(literal.Value);
     }
 }
Example #24
0
		private static bool MatchesFilters(Literal literal, LiteralFilter[] filters, SelectableSource targetModel) {
			foreach (LiteralFilter filter in filters)
				if (!filter.Filter(literal, targetModel))
					return false;
			return true;
		}