public override void Select(StatementSink storage) {
			// Read past the processing instructions to
			// the document element.  If it is rdf:RDF,
			// then process the description nodes within it.
			// Otherwise, the document element is itself a
			// description.
			
			this.storage = storage;
									
			while (xml.Read()) {
				if (xml.NamespaceURI == NS.RDF && xml.LocalName == "RDF" ) {
					// If there is an xml:base here, set BaseUri so
					// the application can recover it.  It doesn't
					// affect parsing since the xml:base attribute
					// will override BaseUri.
					string xmlbase = xml.GetAttribute("xml:base");
					if (xmlbase != null) BaseUri = xmlbase;
					
					while (xml.Read()) {
						if (xml.NodeType == XmlNodeType.Element)
							ParseDescription();
					}
					break;
				}
			}

			xml.Close();
		}
Пример #2
0
 public override void Select(StatementSink storage)
 {
     foreach (RdfReader p in Parsers)
     {
         p.Select(storage);
     }
 }
Пример #3
0
 void StatementSource.Select(StatementSink sink)
 {
     foreach (IStatement statement in Graph.Select(null, null, null))
     {
         sink.Add(Mapper.fromKE(statement));
     }
 }
Пример #4
0
        /// <summary>
        /// Selects all statements from this source and streams them into the given Sink
        /// </summary>
        /// <param name="sink">Statement Sink</param>
        public void Select(StatementSink sink)
        {
            foreach (IGraph g in this._store.Graphs)
            {
                //Get the Hash Code of the Graphs URI and create a new empty mapping if necessary
                Entity graphUri;
                int    hash;
                if (g.BaseUri == null)
                {
                    graphUri = new Entity(GraphCollection.DefaultGraphUri);
                    hash     = new Uri(GraphCollection.DefaultGraphUri).GetEnhancedHashCode();
                }
                else
                {
                    graphUri = new Entity(g.BaseUri.ToString());
                    hash     = g.BaseUri.GetEnhancedHashCode();
                }

                SemWebMapping mapping = this.GetMapping(hash, g);
                foreach (Triple t in g.Triples)
                {
                    Statement stmt = SemWebConverter.ToSemWeb(t, mapping);
                    stmt.Meta = graphUri;
                    if (!sink.Add(stmt))
                    {
                        return;
                    }
                }
            }
        }
Пример #5
0
    public void Select(Statement template, StatementSink sink)
    {
        // extract the fields for easy access
        Entity   subj = template.Subject;
        Entity   pred = template.Predicate;
        Resource obj  = template.Object;

        // convert the SemWeb fields to the RDFQuery fields
        Uri    s;
        string p, o;

        rdf_to_beagle_hook(subj, pred, obj, out s, out p, out o);

        RDFQuery       query  = new RDFQuery(s, p, o);
        RDFQueryResult result = (RDFQueryResult)query.Send();

        foreach (Hit hit in result.Hits)
        {
            Entity subject = new Entity(hit.Uri.ToString());               //FIXME: Do we have to use strings here?
            foreach (Property prop in hit.Properties)
            {
                Entity   predicate = BeaglePropertyToEntity(prop.Type, prop.Key);
                Resource _object;
                property_to_rdf_hook(prop, out _object);

                // now create a the statement and add it to the result
                Statement st = new Statement(subject, predicate, _object);
                sink.Add(st);
            }
        }
    }
Пример #6
0
 /// <summary>
 /// Creates a new Triple Collection as a wrapper around a SemWeb StatementSink and StatementSource
 /// </summary>
 /// <param name="g">Graph</param>
 /// <param name="sink">Sink</param>
 /// <param name="source">Source</param>
 public SemWebTripleCollection(IGraph g, StatementSink sink, StatementSource source) 
 {
     this._g = g;
     this._sink = sink;
     this._source = source;
     this._mapping = new SemWebMapping(this._g);
 }
Пример #7
0
        public static void FindMSG(SelectableSource store, Entity node, StatementSink msg)
        {
            if (node.Uri != null)
            {
                throw new ArgumentException("node must be anonymous");
            }

            ResSet nodesSeen  = new ResSet();
            ResSet nodesToAdd = new ResSet();

            nodesToAdd.Add(node);

            while (nodesToAdd.Count > 0)
            {
                ResSet nodes = nodesToAdd;
                nodesToAdd = new ResSet();

                Sink sink = new Sink(msg, nodesToAdd);
                foreach (Entity n in nodes)
                {
                    if (nodesSeen.Contains(n))
                    {
                        continue;
                    }
                    nodesSeen.Add(n);
                    store.Select(new Statement(n, null, null, null), sink);
                    store.Select(new Statement(null, n, null, null), sink);
                    store.Select(new Statement(null, null, n, null), sink);
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Selects Statements that match a given Template
        /// </summary>
        /// <param name="template">Statement Template</param>
        /// <param name="sink">Sink</param>
        public void Select(Statement template, StatementSink sink)
        {
            //Implement as a SPARQL SELECT
            List <ITriplePattern> patterns = this.TemplateToTriplePatterns(template);
            StringBuilder         query    = new StringBuilder();

            query.AppendLine("SELECT * WHERE {");
            foreach (ITriplePattern pattern in patterns)
            {
                query.AppendLine(pattern.ToString() + ".");
            }
            query.AppendLine("}");

            //Get the Results
            Object results = this._store.ExecuteQuery(query.ToString());

            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Entity    s    = (template.Subject != null) ? template.Subject : SemWebConverter.ToSemWebEntity(r["s"], this._mapping);
                    Entity    p    = (template.Predicate != null) ? template.Predicate : SemWebConverter.ToSemWebEntity(r["p"], this._mapping);
                    Resource  o    = (template.Object != null) ? template.Object : SemWebConverter.ToSemWeb(r["o"], this._mapping);
                    Statement stmt = new Statement(s, p, o);
                    //Keep returning stuff until the sink tells us to stop
                    if (!sink.Add(stmt))
                    {
                        return;
                    }
                }
            }
        }
Пример #9
0
 void SelectableSource.Select(Statement template, StatementSink sink)
 {
     foreach (IStatement statement in Graph.Select(Mapper.toKE(template.Subject), Mapper.toKE(template.Predicate), Mapper.toKE(template.Object)))
     {
         sink.Add(Mapper.fromKE(statement));
     }
 }
Пример #10
0
 /// <summary>
 /// Creates a new Triple Collection as a wrapper around a SemWeb StatementSink and StatementSource
 /// </summary>
 /// <param name="g">Graph</param>
 /// <param name="sink">Sink</param>
 /// <param name="source">Source</param>
 public SemWebTripleCollection(IGraph g, StatementSink sink, StatementSource source)
 {
     this._g       = g;
     this._sink    = sink;
     this._source  = source;
     this._mapping = new SemWebMapping(this._g);
 }
Пример #11
0
        public void Select(SelectFilter filter, StatementSink result)
        {
            // We don't want to select on more than say 1000 resources
            // at a time, so this breaks down the selection into
            // a union of selections that each select on no more than
            // 1000 resources.
            if (result == null)
            {
                throw new ArgumentNullException();
            }

            Init();
            foreach (Entity[] s in SplitArray(filter.Subjects))
            {
                foreach (Entity[] p in SplitArray(filter.Predicates))
                {
                    foreach (Resource[] o in SplitArray(filter.Objects))
                    {
                        foreach (Entity[] m in SplitArray(filter.Metas))
                        {
                            SelectFilter f = new SelectFilter(s, p, o, m);
                            f.LiteralFilters = filter.LiteralFilters;
                            f.Limit          = filter.Limit; // TODO: Do the limit better since it should shrink on each iteration.
                            Select2(f, result);
                        }
                    }
                }
            }
        }
Пример #12
0
	public void Select (Statement template, StatementSink sink)
	{
		// extract the fields for easy access
		Entity subj = template.Subject;
		Entity pred = template.Predicate;
		Resource obj = template.Object;

		// convert the SemWeb fields to the RDFQuery fields
		Uri s;
		string p, o;
		rdf_to_beagle_hook (subj, pred, obj, out s, out p, out o);

		RDFQuery query = new RDFQuery (s, p, o);
		RDFQueryResult result = (RDFQueryResult) query.Send ();
		
		foreach (Hit hit in result.Hits) {
			Entity subject = new Entity (hit.Uri.ToString ()); //FIXME: Do we have to use strings here?
			foreach (Property prop in hit.Properties) {
				Entity predicate = BeaglePropertyToEntity (prop.Type, prop.Key);
				Resource _object;
				property_to_rdf_hook (prop, out _object);
			
				// now create a the statement and add it to the result
				Statement st = new Statement (subject, predicate, _object);
				sink.Add (st);
			}
		}
	}
Пример #13
0
        void WriteGraph(RdfGraph graph, RdfSourceWrapper sourcewrapper, StatementSink sink)
        {
            java.util.Iterator iter = graph.iterator();
            while (iter.hasNext())
            {
                GraphStatement stmt = (GraphStatement)iter.next();
                Statement      s;
                if (stmt is GraphStatementWrapper)
                {
                    s = ((GraphStatementWrapper)stmt).s;
                }
                else
                {
                    s = new Statement(
                        sourcewrapper.ToEntity(stmt.getSubject()),
                        sourcewrapper.ToEntity(stmt.getPredicate()),
                        sourcewrapper.ToResource(stmt.getObject()),
                        stmt.getGraphName() == null ? Statement.DefaultMeta : sourcewrapper.ToEntity(stmt.getGraphName()));
                }

                if (s.AnyNull)
                {
                    continue;                            // unbound variable, or literal in bad position
                }
                sink.Add(s);
            }
        }
Пример #14
0
            public void Select(Statement template, StatementSink result)
            {
                StatementList source = statements;

                // The first time select is called, turn indexing on for the store.
                // TODO: Perform this index in a background thread if there are a lot
                // of statements.
                if (!isIndexed && allowIndexing)
                {
                    isIndexed = true;
                    for (int i = 0; i < StatementCount; i++)
                    {
                        Statement statement = this[i];
                        GetIndexArray(statementsAboutSubject, statement.Subject).Add(statement);
                        GetIndexArray(statementsAboutObject, statement.Object).Add(statement);
                    }
                }

                if (template.Subject != null)
                {
                    ShorterList(ref source, GetIndexArray(statementsAboutSubject, template.Subject));
                }
                else if (template.Object != null)
                {
                    ShorterList(ref source, GetIndexArray(statementsAboutObject, template.Object));
                }

                if (source == null)
                {
                    return;
                }

                bool isRdfsMemberPredicate = (template.Predicate != null && template.Predicate.Uri != null &&
                                              template.Predicate.Uri == NS.RDFS + "member");

                if (isRdfsMemberPredicate)
                {
                    template.Predicate = null;
                }

                for (int i = 0; i < source.Count; i++)
                {
                    Statement statement = source[i];
                    if (!template.Matches(statement))
                    {
                        continue;
                    }

                    if (isRdfsMemberPredicate && (statement.Predicate.Uri == null || !statement.Predicate.Uri.StartsWith(rdfli)))
                    {
                        continue;
                    }

                    if (!result.Add(statement))
                    {
                        return;
                    }
                }
            }
Пример #15
0
        public static void AddLiteral(StatementSink sink, string predicate, string value)
        {
            Statement stmt = new Statement(FSpotXMPBase,
                                           (Entity)MetadataStore.Namespaces.Resolve(predicate),
                                           new SemWeb.Literal(value));

            sink.Add(stmt);
        }
Пример #16
0
 private void Add(StatementSink store, Statement statement, Location position)
 {
     try {
         store.Add(statement);
     } catch (Exception e) {
         OnError("Add failed on statement { " + statement + " }: " + e.Message, position, e);
     }
 }
Пример #17
0
        protected void SelectBySubject(SelectFilter filter, StatementSink sink)
        {
            var selectIdsSourceHash = new Dictionary <SourceDescriptor, IList <object> >();

            for (int i = 0; i < filter.Subjects.Length; i++)
            {
                var subj = filter.Subjects[i];

                foreach (var sourceDescr in FindSourceByItemSubject(subj.Uri))
                {
                    var itemId = ExtractSourceId(sourceDescr, subj.Uri);
                    AddToHashList(selectIdsSourceHash, sourceDescr, itemId);
                }
            }

            foreach (var sourceEntry in selectIdsSourceHash)
            {
                if (filter.Predicates != null)
                {
                    // case 1.1: is predicate is defined
                    var sourceFlds = new List <FieldDescriptor>();
                    for (int i = 0; i < filter.Predicates.Length; i++)
                    {
                        var pred = filter.Predicates[i];
                        // check for "type" predicate
                        if (pred == NS.Rdf.typeEntity)
                        {
                            for (int j = 0; j < sourceEntry.Value.Count; j++)
                            {
                                if (!sink.Add(new Statement(
                                                  GetSourceItemEntity(sourceEntry.Key, sourceEntry.Value[j]),
                                                  pred,
                                                  EntitySourceHash[sourceEntry.Key])))
                                {
                                    return;
                                }
                            }
                            continue;
                        }

                        if (FieldNsSourceHash[sourceEntry.Key].ContainsKey(pred.Uri))
                        {
                            sourceFlds.Add(FieldNsSourceHash[sourceEntry.Key][pred.Uri]);
                        }
                    }
                    if (sourceFlds.Count > 0)
                    {
                        LoadToSink(sourceEntry.Key, sourceEntry.Value, sourceFlds, filter.Objects, sink, filter);
                    }
                }
                else
                {
                    // case 1.2: predicate is undefined
                    LoadToSink(sourceEntry.Key, sourceEntry.Value, null, filter.Objects, sink, filter);
                }
            }
        }
Пример #18
0
        public void Select(Statement template, StatementSink result)
        {
            if (result == null)
            {
                throw new ArgumentNullException();
            }

            Init();
            Select2(new SelectFilter(template), result);
        }
Пример #19
0
 public void Select(Statement template, StatementSink sink)
 {
     if (!selectresults.ContainsKey(template))
     {
         MemoryStore s = new MemoryStore();
         source.Select(template, s);
         selectresults[template] = s;
     }
     ((MemoryStore)selectresults[template]).Select(sink);
 }
Пример #20
0
        public void Select(Statement template, StatementSink sink)
        {
            if (template.Predicate == null)
            {
                data.Select(template, sink);
                return;
            }

            Select(new SelectFilter(template), sink);
        }
Пример #21
0
 public ExpandDomRan(int dr, Hashtable propToType, StatementSink s)
 {
     if (s == null)
     {
         throw new ArgumentNullException();
     }
     domran = dr;
     map    = propToType;
     sink   = s;
 }
Пример #22
0
 public void Select(SelectFilter filter, StatementSink sink)
 {
     if (!selfilterresults.ContainsKey(filter))
     {
         MemoryStore s = new MemoryStore();
         source.Select(filter, s);
         selfilterresults[filter] = s;
     }
     ((MemoryStore)selfilterresults[filter]).Select(sink);
 }
Пример #23
0
		public void Select (StatementSink sink)
		{
			using (Stream stream = Open ()) {
				Header header = new Header (stream);
				MetadataStore.AddLiteral (sink, "tiff:ImageWidth", header.Width.ToString ());
				MetadataStore.AddLiteral (sink, "tiff:ImageLength", header.Height.ToString ());
				string bits = header.IsDeep ? "16" : "8";
				MetadataStore.Add (sink, "tiff:BitsPerSample", "rdf:Seq", new string [] { bits, bits, bits });
			}
		}
Пример #24
0
 public void Select(StatementSink sink)
 {
     using (Stream stream = Open()) {
         Header header = new Header(stream);
         MetadataStore.AddLiteral(sink, "tiff:ImageWidth", header.Width.ToString());
         MetadataStore.AddLiteral(sink, "tiff:ImageLength", header.Height.ToString());
         string bits = header.IsDeep ? "16" : "8";
         MetadataStore.Add(sink, "tiff:BitsPerSample", "rdf:Seq", new string [] { bits, bits, bits });
     }
 }
Пример #25
0
        public override void Select(StatementSink storage)
        {
            // Read past the processing instructions to
            // the document element.  If it is rdf:RDF,
            // then process the description nodes within it.
            // Otherwise, the document element is itself a
            // description.

            this.storage = storage;

            bool first = true;             // on the first iteration don't

            // advance to the next node -- we already did that
            while (first || xml.Read())
            {
                first = false;

                if (xml.NodeType != XmlNodeType.Element)
                {
                    continue;
                }

                if (xml.NamespaceURI == NS.RDF && xml.LocalName == "RDF")
                {
                    // If there is an xml:base here, set BaseUri so
                    // the application can recover it.  It doesn't
                    // affect parsing since the xml:base attribute
                    // will override BaseUri.
                    string xmlbase = xml.GetAttribute("xml:base");
                    if (xmlbase != null)
                    {
                        BaseUri = xmlbase;
                    }

                    while (xml.Read())
                    {
                        if (xml.NodeType == XmlNodeType.Element)
                        {
                            ParseDescription();
                        }
                    }
                }
                else
                {
                    if (xml.LocalName == "RDF")
                    {
                        OnWarning("Document element looks like rdf:RDF but the namespace <" + xml.NamespaceURI + "> is wrong so it is being read as a resource description.");
                    }
                    ParseDescription();
                }
                break;
            }

            Dispose();
        }
Пример #26
0
 /// <summary>
 /// Selects all statements from this source and streams them into the given Sink
 /// </summary>
 /// <param name="sink">Statement Sink</param>
 /// <remarks>
 /// This is essentially the same code as the <see cref="SemWebConverter.ToSemWeb">ToSemWeb(IGraph g, StatementSink sink)</see> function but we need to maintain a consistent mapping of BNodes for the source
 /// </remarks>
 public void Select(StatementSink sink)
 {
     foreach (Triple t in this._g.Triples)
     {
         Statement stmt = SemWebConverter.ToSemWeb(t, this._mapping);
         if (!sink.Add(stmt))
         {
             return;
         }
     }
 }
Пример #27
0
 public override void Select(Statement template, StatementSink sink)
 {
     if (template == Statement.All)
     {
         throw new NotImplementedException();
     }
     else
     {
         SelectSome(template, sink);
     }
 }
		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;
			}
		}
Пример #29
0
 public void Select(StatementSink s)
 {
     if (statements == null)
     {
         source.Select(Statement.All, new Sink(this, s));
     }
     else
     {
         statements.Select(s);
     }
 }
Пример #30
0
		public override void Select(StatementSink store) {
			ParseContext context = new ParseContext();
			context.source = new MyReader(sourcestream);
			context.store = GetDupCheckSink(store);
			context.namespaces = namespaces;
			context.namedNode = new UriMap();
			context.anonymous = new Hashtable();
			context.meta = Meta;
			
			while (ReadStatement(context)) { }
		}
Пример #31
0
        /// <summary>
        /// Takes the contents of a dotNetRDF Graph and inputs it into a SemWeb StatementSink
        /// </summary>
        /// <param name="g">Graph</param>
        /// <param name="mapping">Blank Node Mapping</param>
        /// <param name="sink">Statement Sink</param>
        public static void ToSemWeb(IGraph g, SemWebMapping mapping, StatementSink sink)
        {
            Statement stmt;

            foreach (Triple t in g.Triples)
            {
                stmt = ToSemWeb(t, mapping);
                //Stop adding statements if the sink tells up to stop
                if (!sink.Add(stmt)) return;
            }
        }
Пример #32
0
		bool Select(Statement template, StatementSink sink, bool ask) {
			return Select(
				template.Subject == null ? null : new Entity[] { template.Subject },
				template.Predicate == null ? null : new Entity[] { template.Predicate },
				template.Object == null ? null : new Resource[] { template.Object },
				template.Meta == null ? null : new Entity[] { template.Meta },
				null,
				0,
				sink,
				ask
				);
		}
Пример #33
0
        public void Construct(SelectableSource source, StatementSink sink)
        {
            if (!(query is ConstructQuery))
            {
                throw new InvalidOperationException("Only CONSTRUCT queries are supported by this method (" + query.GetType() + ").");
            }
            ConstructQuery   q             = (ConstructQuery)query;
            RdfSourceWrapper sourcewrapper = new RdfSourceWrapper(source, QueryMeta, this);
            RdfGraph         graph         = q.execute(sourcewrapper);

            WriteGraph(graph, sourcewrapper, sink);
        }
Пример #34
0
        public void Describe(SelectableSource source, StatementSink sink)
        {
            if (!(query is DescribeQuery))
            {
                throw new InvalidOperationException("Only DESCRIBE queries are supported by this method (" + query.GetType() + ").");
            }
            DescribeQuery    q             = (DescribeQuery)query;
            RdfSourceWrapper sourcewrapper = new RdfSourceWrapper(source, QueryMeta, this);
            RdfGraph         graph         = q.execute(sourcewrapper);

            WriteGraph(graph, sourcewrapper, sink);
        }
Пример #35
0
 internal StatementSink GetDupCheckSink(StatementSink sink)
 {
     if (!dupcheck)
     {
         return(sink);
     }
     if (!(sink is Store))
     {
         return(sink);
     }
     return(new DupCheckSink((Store)sink));
 }
Пример #36
0
    void ReadLoop(StatementSink sink)
    {
        while (!finished)
        {
            int nr = nextRead;

            // Check that we can advance (i.e. not cross the write pointer).
            while (nr == nextWrite && !finished)
            {
                if (SLEEP_DURATION > 0)
                {
                    Thread.Sleep(SLEEP_DURATION);
                }
                else
                {
                    hasData.WaitOne();
                }
            }

            if (finished)
            {
                return;
            }

            int nw     = nextWrite;
            int addctr = 0;

            while (nr != nw)
            {
                Statement s = buffer[nr];
                nr = (nr == len - 1) ? 0 : nr + 1;

                if ((addctr++ & 0xFF) == 0)
                {
                    nextRead = nr;
                    hasSpace.Set();
                }

                canceled = !sink.Add(s);
                if (canceled)
                {
                    break;
                }
            }

            nextRead = nr;
            hasSpace.Set();
            if (canceled)
            {
                break;
            }
        }
    }
Пример #37
0
 public override void Select(Statement template, StatementSink result)
 {
     SelectableSource[] sources = GetSources(template.Meta);
     if (sources == null)
     {
         return;
     }
     template.Meta = null;
     foreach (SelectableSource s in sources)
     {
         s.Select(template, result);
     }
 }
Пример #38
0
 bool Select(Statement template, StatementSink sink, bool ask)
 {
     return(Select(
                template.Subject == null ? null : new Entity[] { template.Subject },
                template.Predicate == null ? null : new Entity[] { template.Predicate },
                template.Object == null ? null : new Resource[] { template.Object },
                template.Meta == null ? null : new Entity[] { template.Meta },
                null,
                0,
                sink,
                ask
                ));
 }
Пример #39
0
		public override bool Distinct { get { return false; } } // not sure...
		
		public override void Select(SelectFilter filter, SelectableSource targetModel, StatementSink sink) {
			if (filter.Subjects == null) filter.Subjects = new Entity[] { new Variable("subject") };
			if (filter.Predicates == null) filter.Predicates = new Entity[] { new Variable("predicate") };
			if (filter.Objects == null) filter.Objects = new Entity[] { new Variable("object") };

			if (filter.Metas == null) filter.Metas = new Entity[] { Statement.DefaultMeta };
			
			foreach (Statement s in filter) { // until we can operate on filter directly
				ArrayList evidence = prove(rules, targetModel, new Statement[] { s }, -1);
				if (evidence == null)
					continue; // not provable (in max number of steps, if that were given)
				
				foreach (EvidenceItem ei in evidence) {
					foreach (Statement h in ei.head) { // better be just one statement
						if (filter.LiteralFilters != null
							&& !LiteralFilter.MatchesFilters(h.Object, filter.LiteralFilters, targetModel))
							continue;
						
						sink.Add(h);
					}
				}
			}
		}
Пример #40
0
        /// <summary>
        /// Selects Statements from the Source based on a Template
        /// </summary>
        /// <param name="template">Statement Template</param>
        /// <param name="sink">Sink to stream results to</param>
        public void Select(Statement template, StatementSink sink)
        {
            //Convert Template to an Enumerable
            IEnumerable<Triple> ts = Enumerable.Empty<Triple>();
            int hash;

            if (template.Meta != Statement.DefaultMeta && template.Meta != null)
            {
                //Select from the specific Graph if it exists
                Uri graphUri;
                if (template.Meta.Uri == null)
                {
                    hash = new Uri(GraphCollection.DefaultGraphUri).GetEnhancedHashCode();
                    graphUri = null;
                } 
                else 
                {
                    graphUri = new Uri(template.Meta.Uri);
                    hash = graphUri.GetEnhancedHashCode();
                }
                if (this._store.HasGraph(graphUri))
                {
                    ts = this.TemplateToEnumerable(template, this._store.Graph(graphUri));
                    SemWebMapping mapping = this.GetMapping(hash, this._store.Graph(graphUri));

                    foreach (Triple t in ts)
                    {
                        //Keep streaming Triples until the sink tells us to stop
                        Statement stmt = SemWebConverter.ToSemWeb(t, mapping);
                        if (!sink.Add(stmt)) return;
                    }
                }
            }
            else
            {
                //Output the results from each Graph in turn
                foreach (IGraph g in this._store.Graphs)
                {
                    Entity graphUri;
                    if (g.BaseUri == null) 
                    {
                        hash = new Uri(GraphCollection.DefaultGraphUri).GetEnhancedHashCode();
                        graphUri = new Entity(GraphCollection.DefaultGraphUri);
                    } 
                    else 
                    {
                        hash = g.BaseUri.GetEnhancedHashCode();
                        graphUri = new Entity(g.BaseUri.ToString());
                    }
                    SemWebMapping mapping = this.GetMapping(hash, g);
                    foreach (Triple t in this.TemplateToEnumerable(template, g))
                    {
                        Statement stmt = SemWebConverter.ToSemWeb(t, mapping);
                        stmt.Meta = graphUri;
                        if (!sink.Add(stmt)) return;
                    }
                }
            }
        }
Пример #41
0
        /// <summary>
        /// Selects Statements from the Source based on a Filter
        /// </summary>
        /// <param name="filter">Statement Filter</param>
        /// <param name="sink">Sink to stream results to</param>
        public void Select(SelectFilter filter, StatementSink sink)
        {
            IEnumerable<Triple> ts = Enumerable.Empty<Triple>();
            if (filter.Metas != null)
            {
                //This applies over some Graphs
                foreach (Entity meta in filter.Metas)
                {
                    if (meta.Uri != null)
                    {
                        Uri graphUri = new Uri(meta.Uri);
                        if (this._store.HasGraph(graphUri))
                        {
                            ts = ts.Concat(this.FilterToEnumerable(filter, this._store.Graph(graphUri)));
                        }
                    }
                }
            }
            else
            {
                //This applies over all Graphs
                foreach (IGraph g in this._store.Graphs)
                {
                    ts = ts.Concat(this.FilterToEnumerable(filter, g));
                }
            }

            int count = 0;
            foreach (Triple t in ts)
            {
                //Apply limit if applicable
                if (filter.Limit > 0 && count >= filter.Limit) return;

                Statement stmt = SemWebConverter.ToSemWeb(t, this.GetMapping(t.Graph));
                stmt.Meta = new Entity(t.GraphUri.ToString());

                if (filter.LiteralFilters != null)
                {
                    if (LiteralFilter.MatchesFilters(stmt.Object, filter.LiteralFilters, this))
                    {
                        //If the Object matched the filters then we return the Triple and stop
                        //streaming if the sink tells us to
                        if (!sink.Add(stmt)) return;
                        count++;
                    }
                }
                else
                {
                    //Just add the statement and stop if the sink tells us to stop streaming
                    if (!sink.Add(stmt)) return;
                    count++;
                }
            }
        }
Пример #42
0
		private void Select(Resource templateSubject, Resource templatePredicate, Resource templateObject, Resource templateMeta, LiteralFilter[] litFilters, StatementSink result, int limit) {
			if (result == null) throw new ArgumentNullException();
	
			lock (syncroot) {
			
			Init();
			RunAddBuffer();
			
			// Don't select on columns that we already know from the template.
			// But grab the URIs and literal values for MultiRes selection.
			SelectColumnFilter columns = new SelectColumnFilter();
			columns.SubjectId = (templateSubject == null) || templateSubject is MultiRes;
			columns.PredicateId = (templatePredicate == null) || templatePredicate is MultiRes;
			columns.ObjectId = (templateObject == null) || templateObject is MultiRes;
			columns.MetaId = (templateMeta == null) || templateMeta is MultiRes;
			columns.SubjectUri = templateSubject == null;
			columns.PredicateUri = templatePredicate == null;
			columns.ObjectData = templateObject == null || (templateObject is MultiRes && ((MultiRes)templateObject).ContainsLiterals());
			columns.MetaUri = templateMeta == null;
			
			if (isOrContains(templatePredicate, rdfs_member)) {
				columns.PredicateId = true;
				columns.PredicateUri = true;
			}
			
			// Meta URIs tend to be repeated a lot, so we don't
			// want to ever select them from the database.
			// This preloads them, although it makes the first
			// select quite slow.
			/*if (templateMeta == null && SupportsSubquery) {
				LoadMetaEntities();
				columns.MetaUri = false;
			}*/
			
			// Have to select something
			bool fakeSubjectIdSelect = false;
			if (!columns.SubjectId && !columns.PredicateId && !columns.ObjectId && !columns.MetaId) {
				columns.SubjectId = true;
				fakeSubjectIdSelect = true;
			}
				
			// Pre-cache the IDs of resources in a MultiRes. TODO: Pool these into one array.
			foreach (Resource r in new Resource[] { templateSubject, templatePredicate, templateObject, templateMeta }) {
				MultiRes mr = r as MultiRes;
				if (mr == null) continue;
				PrefetchResourceIds(mr.items);
				CleanMultiRes(mr);
				if (mr.items.Length == 0) // no possible values
					return;
			}
				
			// SQLite has a problem with LEFT JOIN: When a condition is made on the
			// first table in the ON clause (q.objecttype=0/1), when it fails,
			// it excludes the row from the first table, whereas it should only
			// exclude the results of the join.
						
			System.Text.StringBuilder cmd = new System.Text.StringBuilder("SELECT ");
			if (!SupportsLimitClause && limit >= 1) {
				cmd.Append("TOP ");
				cmd.Append(limit);
				cmd.Append(' ');
			}
			if (!HasUniqueStatementsConstraint)
				cmd.Append("DISTINCT ");
			SelectFilterColumns(columns, cmd);
			cmd.Append(" FROM ");
			cmd.Append(table);
			cmd.Append("_statements AS q");
			SelectFilterTables(columns, cmd);
			cmd.Append(' ');
			
			bool wroteWhere;
			if (!WhereClause(templateSubject, templatePredicate, templateObject, templateMeta, cmd, out wroteWhere)) return;
			
			// Transform literal filters into SQL.
			if (litFilters != null) {
				foreach (LiteralFilter f in litFilters) {
					string s = FilterToSQL(f, "lit.value");
					if (s != null) {
						if (!wroteWhere) { cmd.Append(" WHERE "); wroteWhere = true; }
						else { cmd.Append(" AND "); }
						cmd.Append(' ');
						cmd.Append(s);
					}
				}
			}
			
			if (SupportsLimitClause && limit >= 1) {
				cmd.Append(" LIMIT ");
				cmd.Append(limit);
			}

			cmd.Append(';');
			
			if (Debug) {
				string cmd2 = cmd.ToString();
				//if (cmd2.Length > 80) cmd2 = cmd2.Substring(0, 80);
				Console.Error.WriteLine(cmd2);
			}
			
			Hashtable entMap = new Hashtable();
			
			// Be sure if a MultiRes is involved we hash the
			// ids of the entities so we can return them
			// without creating new ones.
			CacheMultiObjects(entMap, templateSubject);
			CacheMultiObjects(entMap, templatePredicate);
			CacheMultiObjects(entMap, templateObject);
			CacheMultiObjects(entMap, templateMeta);
			
			using (IDataReader reader = RunReader(cmd.ToString())) {
				while (reader.Read()) {
					int col = 0;
                    Int64 sid = -1, pid = -1, ot = -1, oid = -1, mid = -1;
					string suri = null, puri = null, ouri = null, muri = null;
					string lv = null, ll = null, ld = null;
					
					if (columns.SubjectId) { sid = reader.GetInt64(col++); }
					if (columns.PredicateId) { pid = reader.GetInt64(col++); }
					if (columns.ObjectId) { oid = reader.GetInt64(col++); }
					if (columns.MetaId) { mid = reader.GetInt64(col++); }
					
					if (columns.SubjectUri) { suri = AsString(reader[col++]); }
					if (columns.PredicateUri) { puri = AsString(reader[col++]); }
					if (columns.ObjectData) { ot = reader.GetInt64(col++); ouri = AsString(reader[col++]); lv = AsString(reader[col++]); ll = AsString(reader[col++]); ld = AsString(reader[col++]);}
					if (columns.MetaUri) { muri = AsString(reader[col++]); }
					
					Entity subject = GetSelectedEntity(sid, suri, templateSubject, columns.SubjectId && !fakeSubjectIdSelect, columns.SubjectUri, entMap);
					Entity predicate = GetSelectedEntity(pid, puri, templatePredicate, columns.PredicateId, columns.PredicateUri, entMap);
					Resource objec = GetSelectedResource(oid, ot, ouri, lv, ll, ld, templateObject, columns.ObjectId, columns.ObjectData, entMap);
					Entity meta = GetSelectedEntity(mid, muri, templateMeta, columns.MetaId, columns.MetaUri, templateMeta != null ? entMap : null);

					if (litFilters != null && !LiteralFilter.MatchesFilters(objec, litFilters, this))
						continue;
						
					bool ret = result.Add(new Statement(subject, predicate, objec, meta));
					if (!ret) break;
				}
			}
			
			} // lock
		}
Пример #43
0
		public void Select(Statement template, StatementSink result) {
			if (result == null) throw new ArgumentNullException();
			Select(template.Subject, template.Predicate, template.Object, template.Meta, null, result, 0);
		}
Пример #44
0
 /// <summary>
 /// Takes the contents of a dotNetRDF Graph and inputs it into a SemWeb StatementSink
 /// </summary>
 /// <param name="g">Graph</param>
 /// <param name="sink">Statement Sink</param>
 public static void ToSemWeb(IGraph g, StatementSink sink)
 {
     SemWebMapping mapping = new SemWebMapping(g);
     ToSemWeb(g, mapping, sink);
 }
Пример #45
0
		public override void Select(SelectFilter filter, SelectableSource targetModel, StatementSink sink) {
			targetModel.Select(filter, sink);
		}
Пример #46
0
		public abstract bool Distinct { get; } // assume targetModel.Distinct is true, *then* would Select be distinct?

		public void Select(Statement template, SelectableSource targetModel, StatementSink sink) {
			Select(new SelectFilter(template), targetModel, sink);
		}
Пример #47
0
		public static void Add (StatementSink sink, string predicate, string type, string [] values)
		{
			Add (sink, FSpotXMPBase, predicate, type, values);
		}
Пример #48
0
		public static void AddLiteral (StatementSink sink, string predicate, string value)
		{
			Statement stmt = new Statement (FSpotXMPBase,
							(Entity)MetadataStore.Namespaces.Resolve (predicate), 
							new SemWeb.Literal (value));
			sink.Add (stmt);
		}
Пример #49
0
		private void Add(StatementSink store, Statement statement, Location position) {
			try {
				store.Add(statement);
			} catch (Exception e) {
				OnError("Add failed on statement { " + statement + " }: " + e.Message, position, e);
			}
		}
Пример #50
0
		public abstract void Select(StatementSink sink);
Пример #51
0
		public override void Select(StatementSink storage) {
			foreach (RdfReader p in Parsers)
				p.Select(storage);
		}
Пример #52
0
	public void Select (SelectFilter filter, StatementSink sink)
	{
		throw new NotImplementedException ("Select");
		// FIXME: not implemented yet, SelectFilter are a little more complex
		// than Statements with wildcards
	}
Пример #53
0
        /// <summary>
        /// Selects all statements from this source and streams them into the given Sink
        /// </summary>
        /// <param name="sink">Statement Sink</param>
        public void Select(StatementSink sink)
        {
            foreach (IGraph g in this._store.Graphs)
            {
                //Get the Hash Code of the Graphs URI and create a new empty mapping if necessary
                Entity graphUri;
                int hash;
                if (g.BaseUri == null)
                {
                    graphUri = new Entity(GraphCollection.DefaultGraphUri);
                    hash = new Uri(GraphCollection.DefaultGraphUri).GetEnhancedHashCode();
                }
                else
                {
                    graphUri = new Entity(g.BaseUri.ToString());
                    hash = g.BaseUri.GetEnhancedHashCode();
                }

                SemWebMapping mapping = this.GetMapping(hash, g);
                foreach (Triple t in g.Triples)
                {
                    Statement stmt = SemWebConverter.ToSemWeb(t, mapping);
                    stmt.Meta = graphUri;
                    if (!sink.Add(stmt)) return;
                }
            }
        }
Пример #54
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);
		}
Пример #55
0
		public void Select (StatementSink sink)
		{
			MetadataStore.AddLiteral (sink, "tiff:Orientation", ((int)Info.Orientation).ToString ());
			MetadataStore.AddLiteral (sink, "tiff:ImageWidth", Info.Width.ToString ());
			MetadataStore.AddLiteral (sink, "tiff:ImageLength", Info.Height.ToString ());
		}
Пример #56
0
		public void Select(StatementSink result) {
			Select(Statement.All, result);
		}
Пример #57
0
		public abstract void Select(SelectFilter filter, SelectableSource targetModel, StatementSink sink);
Пример #58
0
		public void Select(SelectFilter filter, StatementSink result) {
			if (result == null) throw new ArgumentNullException();
			foreach (Entity[] s in SplitArray(filter.Subjects))
			foreach (Entity[] p in SplitArray(filter.Predicates))
			foreach (Resource[] o in SplitArray(filter.Objects))
			foreach (Entity[] m in SplitArray(filter.Metas))
			{
				Select(
					ToMultiRes(s),
					ToMultiRes(p),
					ToMultiRes(o),
					ToMultiRes(m),
					filter.LiteralFilters,
					result,
					filter.Limit); // hmm, repeated
			}
		}
Пример #59
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);
		}
Пример #60
0
	// this simply forwards to a select all
	public void Select (StatementSink sink)
	{
		this.Select (Statement.All, sink);
	}