1 10 package com.hp.hpl.jena.reasoner.rulesys.impl; 11 12 import java.util.NoSuchElementException ; 13 14 import com.hp.hpl.jena.util.iterator.ClosableIterator; 15 16 import java.util.*; 17 18 26 public class LPTopGoalIterator implements ClosableIterator, LPInterpreterContext { 27 28 Object lookAhead; 29 30 31 LPInterpreter interpreter; 32 33 34 protected Set choicePoints = new HashSet(); 35 36 37 protected ConsumerChoicePointFrame nextToRun; 38 39 40 protected boolean isReady = true; 41 42 43 protected boolean checkReadyNeeded = false; 44 45 46 boolean started = false; 47 48 51 public LPTopGoalIterator(LPInterpreter engine) { 52 this.interpreter = engine; 53 engine.setTopInterpreter(this); 55 } 56 57 61 private synchronized void moveForward() { 62 if (interpreter == null || interpreter.getEngine() == null) { 63 throw new ConcurrentModificationException("Call to closed iterator"); 64 } 65 synchronized (interpreter.getEngine()) { 66 68 started = true; 69 71 lookAhead = interpreter.next(); 72 if (lookAhead == StateFlag.FAIL) { 73 if (choicePoints.isEmpty()) { 74 close(); 76 } else { 77 nextToRun = null; 79 interpreter.getEngine().pump(this); 80 if (nextToRun == null) { 81 close(); 83 } else { 84 interpreter.setState(nextToRun); 85 moveForward(); 86 } 87 } 88 } 89 91 } 92 } 93 94 96 public void notifyBlockedOn(ConsumerChoicePointFrame ccp) { 97 choicePoints.add(ccp); 98 checkReadyNeeded = true; 99 } 100 101 105 public void notifyFinished(ConsumerChoicePointFrame ccp) { 106 choicePoints.remove(ccp); 107 checkReadyNeeded = true; 108 } 109 110 114 public void setReady(ConsumerChoicePointFrame ccp) { 115 nextToRun = ccp; 116 isReady = true; 117 checkReadyNeeded = false; 118 } 119 120 124 public boolean isReady() { 125 if (checkReadyNeeded) { 126 isReady = false; 127 for (Iterator i = choicePoints.iterator(); i.hasNext(); ) { 128 ConsumerChoicePointFrame ccp = (ConsumerChoicePointFrame)i.next(); 129 if ( ccp.isReady() ) { 130 if (nextToRun == null) { 131 nextToRun = ccp; 132 } 133 isReady = true; 134 break; 135 } 136 } 137 checkReadyNeeded = false; 138 return isReady; 139 } else { 140 return isReady; 141 } 142 } 143 144 147 public synchronized void close() { 148 if (interpreter != null) { 149 synchronized (interpreter.getEngine()) { 150 152 interpreter.getEngine().checkForCompletions(); 154 lookAhead = null; 156 interpreter.close(); 158 interpreter = null; 160 isReady = false; 161 checkReadyNeeded = false; 162 nextToRun = null; 163 } 166 } 167 } 168 169 172 public boolean hasNext() { 173 if (!started) moveForward(); 174 return (lookAhead != null); 175 } 176 177 180 public Object next() { 181 if (!started) moveForward(); 182 if (lookAhead == null) { 183 throw new NoSuchElementException ("Overran end of LP result set"); 184 } 185 Object result = lookAhead; 186 moveForward(); 187 return result; 188 } 189 190 193 public void remove() { 194 throw new UnsupportedOperationException (); 195 } 196 197 } 198 199 200 201 | Popular Tags |