public static ValueFilter GetValueFilter(Entity predicate, Resource obj) {
			if (predicate == qFilterStringContains && obj is Literal)
				return new StringContainsFilter((Literal)obj);
			if (obj is Literal && (predicate == qFilterLT || predicate == qFilterLE || predicate == qFilterNE || predicate == qFilterEQ || predicate == qFilterGT || predicate == qFilterGE)) {
				Literal lit = (Literal)obj;
				int c = 0; bool e = false;
				if (predicate == qFilterLT || predicate == qFilterLE) c = -1;
				if (predicate == qFilterGT || predicate == qFilterGE) c = 1;
				if (predicate == qFilterLE || predicate == qFilterGE) e = true;
				if (predicate == qFilterEQ) e = true;
				
				if (lit.DataType == null || lit.DataType == "" || lit.DataType == "http://www.w3.org/2001/XMLSchema#string" || lit.DataType == "http://www.w3.org/2001/XMLSchema#normalizedString")
					return new StringCompareFilter(lit, c, e);
				
				if (lit.DataType == "http://www.w3.org/2001/XMLSchema#float" || lit.DataType == "http://www.w3.org/2001/XMLSchema#double" || lit.DataType == "http://www.w3.org/2001/XMLSchema#decimal" || lit.DataType == "http://www.w3.org/2001/XMLSchema#integer" || lit.DataType == "http://www.w3.org/2001/XMLSchema#nonPositiveInteger" || lit.DataType == "http://www.w3.org/2001/XMLSchema#negativeInteger" || lit.DataType == "http://www.w3.org/2001/XMLSchema#long" || lit.DataType == "http://www.w3.org/2001/XMLSchema#int" || lit.DataType == "http://www.w3.org/2001/XMLSchema#short" || lit.DataType == "http://www.w3.org/2001/XMLSchema#byte" || lit.DataType == "http://www.w3.org/2001/XMLSchema#nonNegativeInteger" || lit.DataType == "http://www.w3.org/2001/XMLSchema#unsignedLong" || lit.DataType == "http://www.w3.org/2001/XMLSchema#unsignedInt" || lit.DataType == "http://www.w3.org/2001/XMLSchema#unsignedShort" || lit.DataType == "http://www.w3.org/2001/XMLSchema#unsignedByte" || lit.DataType == "http://www.w3.org/2001/XMLSchema#positiveInteger")
					return new NumericCompareFilter(lit, c, e);
				
				if (lit.DataType == "http://www.w3.org/2001/XMLSchema#dateTime" || lit.DataType == "http://www.w3.org/2001/XMLSchema#date" || lit.DataType == "http://www.w3.org/2001/XMLSchema#time")
					return new DateTimeCompareFilter(lit, c, e);

				if (lit.DataType == "http://www.w3.org/2001/XMLSchema#duration")
					return new TimeSpanCompareFilter(lit, c, e);
			}
			return null;
		}
			public override bool Evaluate(Resource[] args, ref Resource @object) {
				if (args.Length != 1) return false;
				if (args[0] == null && @object == null) return false;
				if ((args[0] != null && !(args[0] is Literal)) || (@object != null && !(@object is Literal))) return false;

				try {
				
				if (args[0] == null) {
					Decimal right = (Decimal)Convert.ChangeType( ((Literal)@object).ParseValue() , typeof(Decimal) );
					Decimal left = EvaluateReverse(right);
					if (left == Decimal.MinValue) return false;
					args[0] = Literal.FromValue(left);
					return true;
				} else {
					Decimal left = (Decimal)Convert.ChangeType( ((Literal)args[0]).ParseValue() , typeof(Decimal) );
					Decimal right  = EvaluateForward(left);
					if (@object == null) {
						@object = Literal.FromValue(right);
						return true;
					} else {
						Decimal right2 = (Decimal)Convert.ChangeType( ((Literal)@object).ParseValue() , typeof(Decimal) );
						return right == right2;
					}
				}
				
				} catch (FormatException) {
					return false;
				}
			}
		private StatementList GetIndexArray(Hashtable from, Resource entity) {
			StatementList ret = (StatementList)from[entity];
			if (ret == null) {
				ret = new StatementList();
				from[entity] = ret;
			}
			return ret;
		}
		bool Select(Entity[] subjects, Entity[] predicates, Resource[] objects, Entity[] metas, LiteralFilter[] litFilters, int limit, StatementSink sink, bool ask) {
			// TODO: Change meta into named graphs.  Anything but a null or DefaultMeta
			// meta returns no statements immediately.
			if (metas != null && (metas.Length != 1 || metas[0] != Statement.DefaultMeta))
				return false;
		
			string query;
			bool nonull = false;
		
			if (subjects != null && subjects.Length == 1
				&& predicates != null && predicates.Length == 1
				&& objects != null && objects.Length == 1) {
				query = "ASK WHERE { " + S(subjects[0], null) + " " + S(predicates[0], null) + " " + S(objects[0], null) + "}";
				nonull = true;
			} else {
				if (ask)
					query = "ASK { ";
				else
					query = "SELECT * WHERE { ";
				query += S(subjects, "?subject");
				query += " ";
				query += S(predicates, "?predicate");
				query += " ";
				query += S(objects, "?object");
				query += " . ";
				query += SL(subjects, "?subject", false);
				query += SL(predicates, "?predicate", false);
				query += SL(objects, "?object", false);
				query += " }";
				
				// TODO: Pass literal filters to server.
			}
			
			if (limit >= 1)
				query += " LIMIT " + limit;
				
			Statement d = new Statement(
				(subjects != null && subjects.Length == 1) ? subjects[0] : null,
				(predicates != null && predicates.Length == 1) ? predicates[0] : null,
				(objects != null && objects.Length == 1) ? objects[0] : null);
			
			if (ask || nonull) {
				BooleanWrap bw = new BooleanWrap();
				Load(query, bw);
				if (ask)
					return bw.value;
				else if (bw.value)
					sink.Add(new Statement(subjects[0], predicates[0], objects[0]));
				return false;
			} else {
				Load(query, new QueryToStatements(sink, litFilters, d));
				return true;
			}
		}
		public Statement Replace(Resource find, Resource replacement) {
			if (replacement is Literal) {
				if (find == Object)
					return new Statement(Subject, Predicate, replacement, Meta);
				return this;
			} else {
				Entity ent = (Entity)replacement;
				return new Statement(
					Subject == find ? ent : Subject,
					Predicate == find ? ent : Predicate,
					Object == find ? ent : Object,
					Meta == find ? ent : Meta
					);
			}
		}
Example #6
0
 /// <summary>
 /// Helper method which converts a SemWeb resource into a PatternItem for use in a SPARQL Triple Pattern
 /// </summary>
 /// <param name="r">Resource</param>
 /// <param name="mapping">Mapping of Variables &amp; Blank Nodes to Pattern Items</param>
 /// <param name="g">Graph</param>
 /// <returns></returns>
 private PatternItem FromSemWeb(Resource r, IGraph g, Dictionary<String, PatternItem> mapping)
 {
     if (r is Variable)
     {
         if (mapping.ContainsKey(r.ToString()))
         {
             return mapping[r.ToString()];
         }
         else
         {
             PatternItem temp = new VariablePattern(r.ToString());
             mapping.Add(r.ToString(), temp);
             return temp;
         }
     }
     else if (r is BNode)
     {
         if (mapping.ContainsKey(r.ToString()))
         {
             return mapping[r.ToString()];
         }
         else
         {
             PatternItem temp = new BlankNodePattern(r.ToString().Substring(2));
             mapping.Add(r.ToString(), temp);
             return temp;
         }
     }
     else
     {
         return new NodeMatchPattern(SemWebConverter.FromSemWeb(r, this.GetMapping(g)));
     }
 }
 /// <summary>
 /// Converts a SemWeb Resource into a dotNetRDF Node
 /// </summary>
 /// <param name="r">Resource</param>
 /// <param name="mapping">Mapping of Blank Nodes</param>
 /// <returns></returns>
 public static INode FromSemWeb(Resource r, SemWebMapping mapping)
 {
     if (r is Entity)
     {
         return FromSemWebEntity((Entity)r, mapping);
     }
     else if (r is Literal)
     {
         Literal lit = (Literal)r;
         if (lit.DataType != null)
         {
             return mapping.Graph.CreateLiteralNode(lit.Value, new Uri(lit.DataType));
         }
         else if (lit.Language != null)
         {
             return mapping.Graph.CreateLiteralNode(lit.Value, lit.Language);
         }
         else
         {
             return mapping.Graph.CreateLiteralNode(lit.Value);
         }
     }
     else
     {
         throw new RdfException("Cannot convert an unknown SemWeb Resource type to a dotNetRDF Node");
     }
 }
		private char ReadPredicate(Resource subject, ParseContext context) {
			bool reverse;
			Location loc = context.Location;
			Resource predicate = ReadResource(context, out reverse);
			if (predicate == null) OnError("Expecting a predicate", loc);
			if (predicate is Literal) OnError("Predicates cannot be literals", loc);
			
			char punctuation = ',';
			while (punctuation == ',') {
				ReadObject(subject, (Entity)predicate, context, reverse);
				loc = context.Location;
				punctuation = ReadPunc(context.source);
			}
			if (punctuation != '.' && punctuation != ';' && punctuation != ']' && punctuation != '}')
				OnError("Expecting a period, semicolon, comma, or close-bracket but found '" + punctuation + "'", loc);
			
			return punctuation;
		}
 /// <summary>
 /// Returns whether the Store contains Statements which contain the given Resource
 /// </summary>
 /// <param name="resource">Resource</param>
 /// <returns></returns>
 public bool Contains(Resource resource)
 {
     //Implemented as a SPARQL ASK
     String query = "ASK WHERE {{" + resource.ToString() + " ?p ?o} UNION {?s " + resource.ToString() + " ?o} UNION {?s ?p " + resource.ToString() + "}}";
     return this.ContainsInternal(query);
 }
Example #10
0
        public override void Run(SelectableSource source, QueryResultSink resultsink)
        {
            if (!(query is SelectQuery))
                throw new InvalidOperationException("Only SELECT queries are supported by this method (" + query.GetType() + ").");

            // Perform the query
            SelectQuery squery = (SelectQuery)query;
            RdfSourceWrapper sourcewrapper = BindLogic(source);

            RdfBindingSet results;
            try {
                results = squery.execute(sourcewrapper);
            } catch (name.levering.ryan.sparql.common.QueryException e) {
                throw new QueryExecutionException("Error executing query: " + e.Message, e);
            }

            // Prepare binding objects
            java.util.List vars = results.getVariables();
            SparqlVariable[] svars = new SparqlVariable[vars.size()];
            SemWebVariable[] vars2 = new SemWebVariable[vars.size()];
            for (int i = 0; i < svars.Length; i++) {
                svars[i] = (SparqlVariable)vars.get(i);
                vars2[i] = new SemWebVariable(svars[i].getName());
            }

            // Initialize the result sink
            resultsink.Init(vars2); // set distinct and ordered

            // Set the comments
            resultsink.AddComments(queryString + "\n");
            resultsink.AddComments(sourcewrapper.GetLog());

            // Iterate the bindings
            java.util.Iterator iter = results.iterator();
            long ctr = -1, ctr2 = 0;
            while (iter.hasNext()) {
                RdfBindingRow row = (RdfBindingRow)iter.next();

                // Since SPARQL processing may be lazy-delayed,
                // add any new comments that might have been logged.
                resultsink.AddComments(sourcewrapper.GetLog());

                ctr++;

                if (ctr < ReturnStart && ReturnStart != -1) continue;

                Resource[] bindings = new Resource[vars2.Length];

                for (int i = 0; i < bindings.Length; i++) {
                    Resource r = sourcewrapper.ToResource(row.getValue(svars[i]));
                    r = sourcewrapper.Persist(r);
                    bindings[i] = r;
                }

                resultsink.AddComments(sourcewrapper.GetLog());

                resultsink.Add(new VariableBindings(vars2, bindings));

                ctr2++;
                if (ctr2 >= ReturnLimit && ReturnLimit != -1) break;
            }

            resultsink.AddComments(sourcewrapper.GetLog());

            // Close the result sink.
            resultsink.Finished();
        }
Example #11
0
            private java.util.Iterator GetIterator(Entity[] subjects, Entity[] predicates, Resource[] objects, Entity[] metas, object[] litFilters, int limit)
            {
                if (subjects == null && predicates == null && objects == null && limit == -1)
                    throw new QueryExecutionException("Query would select all statements in the store!");

                if (subjects != null) Depersist(subjects);
                if (predicates != null) Depersist(predicates);
                if (objects != null) Depersist(objects);
                if (metas != null) Depersist(metas);

                if (subjects != null && subjects.Length == 0) return new EmptyIterator();
                if (predicates != null && predicates.Length == 0) return new EmptyIterator();
                if (objects != null && objects.Length == 0) return new EmptyIterator();
                if (metas != null && metas.Length == 0) return new EmptyIterator();

                SelectFilter filter = new SelectFilter(subjects, predicates, objects, metas);
                if (litFilters != null) {
                    filter.LiteralFilters = new LiteralFilter[litFilters.Length];
                    for (int i = 0; i < litFilters.Length; i++)
                        filter.LiteralFilters[i] = (LiteralFilter)litFilters[i];
                }
                if (limit == 0)
                    filter.Limit = 1;
                else if (limit > 0)
                    filter.Limit = limit;

                return new StatementIterator(source, filter, this);
            }
Example #12
0
 public Resource[] ToResources(name.levering.ryan.sparql.common.Value[] ents)
 {
     if (ents == null) return null;
     Resource[] ret = new Resource[ents.Length];
     for (int i = 0; i < ents.Length; i++)
         ret[i] = ToResource(ents[i]);
     return ret;
 }
Example #13
0
			public Resource Depersist(Resource r) {
				if (r.Uri == null || !sparql.AllowPersistBNodes) return r;
				if (!(source is SupportsPersistableBNodes)) return r;
				if (!r.Uri.StartsWith(Sparql.BNodePersistUri)) return r;
				
				SupportsPersistableBNodes spb = (SupportsPersistableBNodes)source;
				string uri = r.Uri;
				string guid = uri.Substring(Sparql.BNodePersistUri.Length);
				int c = guid.IndexOf(':');
				if (c > 0) {
					string id = guid.Substring(c+1);
					guid = guid.Substring(0, c);
					if (spb.GetStoreGuid() != null && guid == spb.GetStoreGuid()) {
						BNode node = spb.GetNodeFromId(id);
						if (node != null)
							return node;
					}
				}
				
				return r;
			}
Example #14
0
			public Resource[] ToResources(org.openrdf.model.Value[] ents) {
				if (ents == null) return null;
				Resource[] ret = new Resource[ents.Length];
				for (int i = 0; i < ents.Length; i++)
					ret[i] = ToResource(ents[i]);
				return ret;
			}
Example #15
0
 protected void SetResourceKey(Resource resource, object value)
 {
     resource.SetResourceKey(this, value);
 }
Example #16
0
			public Resource Persist(Resource r) {
				if (!(r is BNode) || !sparql.AllowPersistBNodes) return r;
				if (!(source is SupportsPersistableBNodes)) return r;
				SupportsPersistableBNodes spb = (SupportsPersistableBNodes)source;
				string guid = spb.GetStoreGuid();
				if (guid == null) return r;
				string id = spb.GetNodeId((BNode)r);
				if (id == null) return r;
				return new Entity(Sparql.BNodePersistUri + guid + ":" + id);
			}
Example #17
0
 public Resource Persist(Resource r)
 {
     if (!(r is BNode) || !sparql.AllowPersistBNodes) return r;
     if (!(source is StaticSource)) return r;
     StaticSource spb = (StaticSource)source;
     string id = spb.GetPersistentBNodeId((BNode)r);
     if (id == null) return r;
     return new Entity(SparqlEngine.BNodePersistUri + ":" + id);
 }
Example #18
0
			public static org.openrdf.model.Value Wrap(Resource res) {
				if (res is Literal)
					return new LiteralWrapper((Literal)res);
				else if (res.Uri == null)
					return new BNodeWrapper((BNode)res);
				else
					return new URIWrapper((Entity)res);
			}
Example #19
0
 public Resource[] ToResources(name.levering.ryan.sparql.model.logic.ExpressionLogic[] ents, name.levering.ryan.sparql.common.RdfBindingRow binding)
 {
     if (ents == null) return null;
     Resource[] ret = new Resource[ents.Length];
     for (int i = 0; i < ents.Length; i++) {
         if (ents[i] is SparqlVariable)
             ret[i] = ToResource(binding.getValue((SparqlVariable)ents[i]));
         else
             ret[i] = ToResource((name.levering.ryan.sparql.common.Value)ents[i]);
     }
     return ret;
 }
Example #20
0
		protected object GetResourceKey(Resource resource) {
			return resource.GetResourceKey(this);
		}
Example #21
0
 public override Resource Evaluate(Resource[] args)
 {
     return Literal.FromValue(args.Length == 2 && args[0].Equals(args[1]));
 }
Example #22
0
		protected void SetResourceKey(Resource resource, object value) {
			resource.SetResourceKey(this, value);
		}
Example #23
0
 public override Resource Evaluate(Resource[] args)
 {
     if (args.Length != 1 || !(args[0] is Literal)) throw new InvalidOperationException();
     return new Literal(((Literal)args[0]).Value.ToLower());
 }
Example #24
0
 public static name.levering.ryan.sparql.common.Value Wrap(Resource res, Hashtable cache)
 {
     if (cache.ContainsKey(res))
         return (name.levering.ryan.sparql.common.Value)cache[res];
     name.levering.ryan.sparql.common.Value value = Wrap(res);
     cache[res] = value;
     return value;
 }
		private char ReadPredicates(Resource subject, ParseContext context) {			
			char punctuation = ';';
			while (punctuation == ';')
				punctuation = ReadPredicate(subject, context);
			return punctuation;
		}
Example #26
0
 public static name.levering.ryan.sparql.common.Value Wrap(Resource res)
 {
     if (res is Literal)
         return new LiteralWrapper((Literal)res);
     else if (res.Uri == null)
         return new BNodeWrapper((BNode)res);
     else
         return new URIWrapper((Entity)res);
 }
		private void ReadObject(Resource subject, Entity predicate, ParseContext context, bool reverse) {
			bool reverse2;
			Location loc = context.Location;
			Resource value = ReadResource(context, out reverse2);
			if (value == null) OnError("Expecting a resource or literal object", loc);
			if (reverse2) OnError("is...of not allowed on objects", loc);
			
			loc = context.Location;
			if (!reverse) {
				if (subject is Literal) OnError("Subjects of statements cannot be literals", loc);			
				Add(context.store, new Statement((Entity)subject, predicate, value, context.meta), loc);
			} else {
				if (value is Literal) OnError("A literal cannot be the object of a reverse-predicate statement", loc);
				Add(context.store, new Statement((Entity)value, predicate, subject, context.meta), loc);
			}
		}
Example #28
0
 public void Depersist(Resource[] r)
 {
     for (int i = 0; i < r.Length; i++)
         r[i] = Depersist(r[i]);
 }
Example #29
0
        /// <summary>
        /// Returns whether the Source contains any Statement which contains the given Resource
        /// </summary>
        /// <param name="resource">Resource</param>
        /// <returns></returns>
        public bool Contains(Resource resource)
        {
            //Have to check against each Graph until we find a match
            foreach (IGraph g in this._store.Graphs)
            {
                //First we need to convert the Resource to a Node
                INode n = SemWebConverter.FromSemWeb(resource, this.GetMapping(g));

                if (g.Nodes.Contains(n))
                {
                    //If it's in the Node collection check that a Triple with the given Node exists
                    if (g.Triples.Any(t => t.Involves(n))) return true;
                }
            }

            //If none of the Graphs contained it we return false
            return false;
        }
Example #30
0
            public Resource Depersist(Resource r)
            {
                if (r.Uri == null || !sparql.AllowPersistBNodes) return r;
                if (!(source is StaticSource)) return r;
                if (!r.Uri.StartsWith(SparqlEngine.BNodePersistUri)) return r;

                StaticSource spb = (StaticSource)source;
                string uri = r.Uri;
                string id = uri.Substring(SparqlEngine.BNodePersistUri.Length);
                BNode node = spb.GetBNodeFromPersistentId(id);
                if (node != null)
                    return node;

                return r;
            }
 /// <summary>
 /// Writes the specified resource to the output writer.
 /// </summary>
 /// <param name="resource">The resource.</param>
 protected virtual void WriteResource(Resource resource)
 {
     if (resource is Entity)
         WriteEntity((Entity)resource);
     else
         WriteLiteral((Literal)resource);
 }
Example #32
0
 protected object GetResourceKey(Resource resource)
 {
     return(resource.GetResourceKey(this));
 }