<commit_before>/******************************************************************
 * File:        LPTopGoalIterator.java
 * Created by:  <NAME>
 * Created on:  21-Jul-2003
 *
 * (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
 * [See end of file]
 * $Id: LPTopGoalIterator.java,v 1.7 2005-04-08 17:38:51 ian_dickinson Exp $
 *****************************************************************/
package com.hp.hpl.jena.reasoner.rulesys.impl;

import java.util.NoSuchElementException;

import com.hp.hpl.jena.util.iterator.ClosableIterator;

import java.util.*;

import org.apache.commons.logging.LogFactory;

/**
 * Wraps up the results an LP rule engine instance into a conventional
 * iterator. Ensures that the engine is closed and detached from the
 * inference graph if the iterator hits the end of the result set.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @version $Revision: 1.7 $ on $Date: 2005-04-08 17:38:51 $
 */
public class LPTopGoalIterator implements ClosableIterator, LPInterpreterContext {
    /** The next result to be returned, or null if we have finished */
    Object lookAhead;

    /** The parent backward chaining engine */
    LPInterpreter interpreter;

    /** The set of choice points that the top level interpter is waiting for */
    protected Set choicePoints = new HashSet();

    /** The choice point most recently notified as ready to run. */
    protected ConsumerChoicePointFrame nextToRun;

    /** set to true if we should be able to usefully run */
    protected boolean isReady = true;

    /** set to true if at least one branch has block so an active readiness check is required */
    protected boolean checkReadyNeeded = false;

    /** True if the iteration has started */
    boolean started = false;

    /**
     * Constructor. Wraps a top level goal state as an iterator
     */
    public LPTopGoalIterator(LPInterpreter engine) {
        this.interpreter = engine;
//        engine.setState(this);
        engine.setTopInterpreter(this);
    }

    /**
     * Find the next result in the goal state and put it in the
     * lookahead buffer.
     */
    private void moveForward() {
        synchronized (interpreter.getEngine()) {
            // LogFactory.getLog( getClass() ).debug( "Entering moveForward sync block on " + interpreter.getEngine() );

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

            lookAhead = interpreter.next();
            if (lookAhead == StateFlag.FAIL) {
                if (choicePoints.isEmpty()) {
                    // Nothing left to try
                    close();
                } else {
                    // Some options open, continue pumping
                    nextToRun = null;
                    interpreter.getEngine().pump(this);
                    if (nextToRun == null) {
                        // Reached final closure
                        close();
                    } else {
                        interpreter.setState(nextToRun);
                        moveForward();
                    }
                }
            }
            // LogFactory.getLog( getClass() ).debug( "Leaving moveForward sync block " );

        }
    }

    /** Notify this context that a brach was suspended awaiting futher
     *  results from the given generator. */
    public void notifyBlockedOn(ConsumerChoicePointFrame ccp) {
        choicePoints.add(ccp);
        checkReadyNeeded = true;
    }

    /**
     * Notify this context that the given choice point has terminated
     * and can be remove from the wait list.
     */
    public void notifyFinished(ConsumerChoicePointFrame ccp) {
        choicePoints.remove(ccp);
        checkReadyNeeded = true;
    }

    /**
     * Directly set that this generator is ready (because the generating
     * for one of its generatingCPs has produced new results).
     */
    public void setReady(ConsumerChoicePointFrame ccp) {
        nextToRun = ccp;
        isReady = true;
        checkReadyNeeded = false;
    }

    /**
     * Return true if the iterator is ready to be scheduled (i.e. it is not
     * known to be complete and not known to be waiting for a dependent generator).
     */
    public boolean isReady() {
        if (checkReadyNeeded) {
            isReady = false;
            for (Iterator i = choicePoints.iterator(); i.hasNext(); ) {
                ConsumerChoicePointFrame ccp = (ConsumerChoicePointFrame)i.next();
                if ( ccp.isReady() ) {
                    if (nextToRun == null) {
                        nextToRun = ccp;
                    }
                    isReady =  true;
                    break;
                }
            }
            checkReadyNeeded = false;
            return isReady;
        } else {
            return isReady;
        }
    }

    /**
     * @see com.hp.hpl.jena.util.iterator.ClosableIterator#close()
     */
    public void close() {
        if (interpreter != null) {
            synchronized (interpreter.getEngine()) {
                // LogFactory.getLog( getClass() ).debug( "Entering close sync block on " + interpreter.getEngine() );

                // Check for any dangling generators which are complete
                interpreter.getEngine().checkForCompletions();
                // Close this top goal
                lookAhead = null;
                //LogFactory.getLog( getClass() ).debug( "Nulling and closing LPTopGoalIterator " + interpreter );
                interpreter.close();
                // was TEMP experiment: interpreter.getEngine().detach(interpreter);
                interpreter = null;
                isReady = false;
                checkReadyNeeded = false;
                nextToRun = null;
//                choicePoints = null;  // disabled to prevent async close causing problems
                //LogFactory.getLog( getClass() ).debug( "Leaving close sync block " );
            }
        }
    }
<commit_msg>Added check for accessing closed LPTopGoalIterator, top to turn NPE into a CME<commit_after>/******************************************************************
 * File:        LPTopGoalIterator.java
 * Created by:  <NAME>
 * Created on:  21-Jul-2003
 *
 * (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
 * [See end of file]
 * $Id: LPTopGoalIterator.java,v 1.8 2005-04-11 11:04:49 der Exp $
 *****************************************************************/
package com.hp.hpl.jena.reasoner.rulesys.impl;

import java.util.NoSuchElementException;

import com.hp.hpl.jena.util.iterator.ClosableIterator;

import java.util.*;

import org.apache.commons.logging.LogFactory;

/**
 * Wraps up the results an LP rule engine instance into a conventional
 * iterator. Ensures that the engine is closed and detached from the
 * inference graph if the iterator hits the end of the result set.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @version $Revision: 1.8 $ on $Date: 2005-04-11 11:04:49 $
 */
public class LPTopGoalIterator implements ClosableIterator, LPInterpreterContext {
    /** The next result to be returned, or null if we have finished */
    Object lookAhead;

    /** The parent backward chaining engine */
    LPInterpreter interpreter;

    /** The set of choice points that the top level interpter is waiting for */
    protected Set choicePoints = new HashSet();

    /** The choice point most recently notified as ready to run. */
    protected ConsumerChoicePointFrame nextToRun;

    /** set to true if we should be able to usefully run */
    protected boolean isReady = true;

    /** set to true if at least one branch has block so an active readiness check is required */
    protected boolean checkReadyNeeded = false;

    /** True if the iteration has started */
    boolean started = false;

    /**
     * Constructor. Wraps a top level goal state as an iterator
     */
    public LPTopGoalIterator(LPInterpreter engine) {
        this.interpreter = engine;
//        engine.setState(this);
        engine.setTopInterpreter(this);
    }

    /**
     * Find the next result in the goal state and put it in the
     * lookahead buffer.
     */
    private synchronized void moveForward() {
        if (interpreter == null || interpreter.getEngine() == null) {
            throw new ConcurrentModificationException("Call to closed iterator");
        }
        synchronized (interpreter.getEngine()) {
            // LogFactory.getLog( getClass() ).debug( "Entering moveForward sync block on " + interpreter.getEngine() );

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

            lookAhead = interpreter.next();
            if (lookAhead == StateFlag.FAIL) {
                if (choicePoints.isEmpty()) {
                    // Nothing left to try
                    close();
                } else {
                    // Some options open, continue pumping
                    nextToRun = null;
                    interpreter.getEngine().pump(this);
                    if (nextToRun == null) {
                        // Reached final closure
                        close();
                    } else {
                        interpreter.setState(nextToRun);
                        moveForward();
                    }
                }
            }
            // LogFactory.getLog( getClass() ).debug( "Leaving moveForward sync block " );

        }
    }

    /** Notify this context that a brach was suspended awaiting futher
     *  results from the given generator. */
    public void notifyBlockedOn(ConsumerChoicePointFrame ccp) {
        choicePoints.add(ccp);
        checkReadyNeeded = true;
    }

    /**
     * Notify this context that the given choice point has terminated
     * and can be remove from the wait list.
     */
    public void notifyFinished(ConsumerChoicePointFrame ccp) {
        choicePoints.remove(ccp);
        checkReadyNeeded = true;
    }

    /**
     * Directly set that this generator is ready (because the generating
     * for one of its generatingCPs has produced new results).
     */
    public void setReady(ConsumerChoicePointFrame ccp) {
        nextToRun = ccp;
        isReady = true;
        checkReadyNeeded = false;
    }

    /**
     * Return true if the iterator is ready to be scheduled (i.e. it is not
     * known to be complete and not known to be waiting for a dependent generator).
     */
    public boolean isReady() {
        if (checkReadyNeeded) {
            isReady = false;
            for (Iterator i = choicePoints.iterator(); i.hasNext(); ) {
                ConsumerChoicePointFrame ccp = (ConsumerChoicePointFrame)i.next();
                if ( ccp.isReady() ) {
                    if (nextToRun == null) {
                        nextToRun = ccp;
                    }
                    isReady =  true;
                    break;
                }
            }
            checkReadyNeeded = false;
            return isReady;
        } else {
            return isReady;
        }
    }

    /**
     * @see com.hp.hpl.jena.util.iterator.ClosableIterator#close()
     */
    public synchronized void close() {
        if (interpreter != null) {
            synchronized (interpreter.getEngine()) {
                // LogFactory.getLog( getClass() ).debug( "Entering close sync block on " + interpreter.getEngine() );

                // Check for any dangling generators which are complete
                interpreter.getEngine().checkForCompletions();
                // Close this top goal
                lookAhead = null;
                //LogFactory.getLog( getClass() ).debug( "Nulling and closing LPTopGoalIterator " + interpreter );
                interpreter.close();
                // was TEMP experiment: interpreter.getEngine().detach(interpreter);
                interpreter = null;
                isReady = false;
                checkReadyNeeded = false;
                nextToRun = null;
//                choicePoints = null;  // disabled to prevent async close causing problems
                //LogFactory.getLog( getClass() ).debug( "Leaving close sync block " );
            }
        }
    }

{'fraction_non_alphanumeric': 0.11154694778131895, 'fraction_numerical': 0.008171937566396992, 'mean_word_length': 1.9263510282161644, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3955799', 'n_tokens_mistral': 3277, 'n_tokens_neox': 3086, 'n_words': 995}