KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > reasoner > rulesys > impl > LPTopGoalIterator


1 /******************************************************************
2  * File: LPTopGoalIterator.java
3  * Created by: Dave Reynolds
4  * Created on: 21-Jul-2003
5  *
6  * (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
7  * [See end of file]
8  * $Id: LPTopGoalIterator.java,v 1.9 2005/04/11 11:29:12 der Exp $
9  *****************************************************************/

10 package com.hp.hpl.jena.reasoner.rulesys.impl;
11
12 import java.util.NoSuchElementException JavaDoc;
13
14 import com.hp.hpl.jena.util.iterator.ClosableIterator;
15
16 import java.util.*;
17
18 /**
19  * Wraps up the results an LP rule engine instance into a conventional
20  * iterator. Ensures that the engine is closed and detached from the
21  * inference graph if the iterator hits the end of the result set.
22  *
23  * @author <a HREF="mailto:der@hplb.hpl.hp.com">Dave Reynolds</a>
24  * @version $Revision: 1.9 $ on $Date: 2005/04/11 11:29:12 $
25  */

26 public class LPTopGoalIterator implements ClosableIterator, LPInterpreterContext {
27     /** The next result to be returned, or null if we have finished */
28     Object JavaDoc lookAhead;
29
30     /** The parent backward chaining engine */
31     LPInterpreter interpreter;
32
33     /** The set of choice points that the top level interpter is waiting for */
34     protected Set choicePoints = new HashSet();
35
36     /** The choice point most recently notified as ready to run. */
37     protected ConsumerChoicePointFrame nextToRun;
38
39     /** set to true if we should be able to usefully run */
40     protected boolean isReady = true;
41
42     /** set to true if at least one branch has block so an active readiness check is required */
43     protected boolean checkReadyNeeded = false;
44
45     /** True if the iteration has started */
46     boolean started = false;
47
48     /**
49      * Constructor. Wraps a top level goal state as an iterator
50      */

51     public LPTopGoalIterator(LPInterpreter engine) {
52         this.interpreter = engine;
53 // engine.setState(this);
54
engine.setTopInterpreter(this);
55     }
56
57     /**
58      * Find the next result in the goal state and put it in the
59      * lookahead buffer.
60      */

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             // LogFactory.getLog( getClass() ).debug( "Entering moveForward sync block on " + interpreter.getEngine() );
67

68             started = true;
69             // LogFactory.getLog( getClass() ).debug( "interpreter = " + interpreter );
70

71             lookAhead = interpreter.next();
72             if (lookAhead == StateFlag.FAIL) {
73                 if (choicePoints.isEmpty()) {
74                     // Nothing left to try
75
close();
76                 } else {
77                     // Some options open, continue pumping
78
nextToRun = null;
79                     interpreter.getEngine().pump(this);
80                     if (nextToRun == null) {
81                         // Reached final closure
82
close();
83                     } else {
84                         interpreter.setState(nextToRun);
85                         moveForward();
86                     }
87                 }
88             }
89             // LogFactory.getLog( getClass() ).debug( "Leaving moveForward sync block " );
90

91         }
92     }
93
94     /** Notify this context that a brach was suspended awaiting futher
95      * results from the given generator. */

96     public void notifyBlockedOn(ConsumerChoicePointFrame ccp) {
97         choicePoints.add(ccp);
98         checkReadyNeeded = true;
99     }
100
101     /**
102      * Notify this context that the given choice point has terminated
103      * and can be remove from the wait list.
104      */

105     public void notifyFinished(ConsumerChoicePointFrame ccp) {
106         choicePoints.remove(ccp);
107         checkReadyNeeded = true;
108     }
109
110     /**
111      * Directly set that this generator is ready (because the generating
112      * for one of its generatingCPs has produced new results).
113      */

114     public void setReady(ConsumerChoicePointFrame ccp) {
115         nextToRun = ccp;
116         isReady = true;
117         checkReadyNeeded = false;
118     }
119
120     /**
121      * Return true if the iterator is ready to be scheduled (i.e. it is not
122      * known to be complete and not known to be waiting for a dependent generator).
123      */

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     /**
145      * @see com.hp.hpl.jena.util.iterator.ClosableIterator#close()
146      */

147     public synchronized void close() {
148         if (interpreter != null) {
149             synchronized (interpreter.getEngine()) {
150                 // LogFactory.getLog( getClass() ).debug( "Entering close sync block on " + interpreter.getEngine() );
151

152                 // Check for any dangling generators which are complete
153
interpreter.getEngine().checkForCompletions();
154                 // Close this top goal
155
lookAhead = null;
156                 //LogFactory.getLog( getClass() ).debug( "Nulling and closing LPTopGoalIterator " + interpreter );
157
interpreter.close();
158                 // was TEMP experiment: interpreter.getEngine().detach(interpreter);
159
interpreter = null;
160                 isReady = false;
161                 checkReadyNeeded = false;
162                 nextToRun = null;
163 // choicePoints = null; // disabled to prevent async close causing problems
164
//LogFactory.getLog( getClass() ).debug( "Leaving close sync block " );
165
}
166         }
167     }
168
169     /**
170      * @see java.util.Iterator#hasNext()
171      */

172     public boolean hasNext() {
173         if (!started) moveForward();
174         return (lookAhead != null);
175     }
176
177     /**
178      * @see java.util.Iterator#next()
179      */

180     public Object JavaDoc next() {
181         if (!started) moveForward();
182         if (lookAhead == null) {
183             throw new NoSuchElementException JavaDoc("Overran end of LP result set");
184         }
185         Object JavaDoc result = lookAhead;
186         moveForward();
187         return result;
188     }
189
190     /**
191      * @see java.util.Iterator#remove()
192      */

193     public void remove() {
194         throw new UnsupportedOperationException JavaDoc();
195     }
196
197 }
198
199
200
201 /*
202     (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
203     All rights reserved.
204
205     Redistribution and use in source and binary forms, with or without
206     modification, are permitted provided that the following conditions
207     are met:
208
209     1. Redistributions of source code must retain the above copyright
210        notice, this list of conditions and the following disclaimer.
211
212     2. Redistributions in binary form must reproduce the above copyright
213        notice, this list of conditions and the following disclaimer in the
214        documentation and/or other materials provided with the distribution.
215
216     3. The name of the author may not be used to endorse or promote products
217        derived from this software without specific prior written permission.
218
219     THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
220     IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
221     OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
222     IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
223     INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
224     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
225     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
226     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
227     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
228     THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
229 */
Popular Tags