1 6 7 package com.hp.hpl.jena.graph.query; 8 9 import com.hp.hpl.jena.graph.*; 10 import com.hp.hpl.jena.util.CollectionFactory; 11 import com.hp.hpl.jena.util.iterator.*; 12 import com.hp.hpl.jena.mem.*; 13 import java.util.*; 14 15 18 public class SimpleTreeQueryPlan implements TreeQueryPlan 19 { 20 private Graph pattern; 21 private Graph target; 22 23 public SimpleTreeQueryPlan( Graph target, Graph pattern ) 24 { 25 this.target = target; 26 this.pattern = pattern; 27 } 28 29 public Graph executeTree() 30 { 31 Graph result = new GraphMem(); 32 Set roots = getRoots( pattern ); 33 for (Iterator it = roots.iterator(); it.hasNext(); handleRoot( result, (Node) it.next(), CollectionFactory.createHashedSet())) {} 34 return result; 35 } 36 37 private Iterator findFromTriple( Graph g, Triple t ) 38 { 39 return g.find( asPattern( t.getSubject() ), asPattern( t.getPredicate() ), asPattern( t.getObject() ) ); 40 } 41 42 private Node asPattern( Node x ) 43 { return x.isBlank() ? null : x; } 44 45 private void handleRoot( Graph result, Node root, Set pending ) 46 { 47 ClosableIterator it = pattern.find( root, null, null ); 48 if (!it.hasNext()) 49 { 50 absorb( result, pending ); 51 return; 52 } 53 while (it.hasNext()) 54 { 55 Triple base = (Triple) it.next(); 56 Iterator that = findFromTriple( target, base ); while (that.hasNext()) 58 { 59 Triple x = (Triple) that.next(); 60 pending.add( x ); 61 handleRoot( result, base.getObject(), pending ); 62 } 63 } 64 } 65 66 private void absorb( Graph result, Set triples ) 67 { 68 for (Iterator it = triples.iterator(); it.hasNext(); result.add( (Triple) it.next())) {} 69 triples.clear(); 70 } 71 72 public static Set getRoots( Graph pattern ) 73 { 74 Set roots = CollectionFactory.createHashedSet(); 75 ClosableIterator sub = GraphUtil.findAll( pattern ); 76 while (sub.hasNext()) roots.add( ((Triple) sub.next()).getSubject() ); 77 ClosableIterator obj = GraphUtil.findAll( pattern ); 78 while (obj.hasNext()) roots.remove( ((Triple) obj.next()).getObject() ); 79 return roots; 80 } 81 } 82 111 | Popular Tags |