⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 abstractworkingmemory.java

📁 jboss规则引擎
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
package org.drools.common;

/*
 * Copyright 2005 JBoss Inc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.drools.Agenda;
import org.drools.FactException;
import org.drools.FactHandle;
import org.drools.NoSuchFactHandleException;
import org.drools.NoSuchFactObjectException;
import org.drools.QueryResults;
import org.drools.RuleBase;
import org.drools.RuleBaseConfiguration;
import org.drools.WorkingMemory;
import org.drools.event.AgendaEventListener;
import org.drools.event.AgendaEventSupport;
import org.drools.event.WorkingMemoryEventListener;
import org.drools.event.WorkingMemoryEventSupport;
import org.drools.rule.Rule;
import org.drools.spi.Activation;
import org.drools.spi.AgendaFilter;
import org.drools.spi.AgendaGroup;
import org.drools.spi.AsyncExceptionHandler;
import org.drools.spi.FactHandleFactory;
import org.drools.spi.PropagationContext;
import org.drools.util.FastMap;
import org.drools.util.PrimitiveLongMap;
import org.drools.util.concurrent.locks.Lock;
import org.drools.util.concurrent.locks.ReentrantLock;

/**
 * Implementation of <code>WorkingMemory</code>.
 * 
 * @author <a href="mailto:bob@werken.com">bob mcwhirter </a>
 * @author <a href="mailto:mark.proctor@jboss.com">Mark Proctor</a>
 * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris </a>
 */
public abstract class AbstractWorkingMemory
    implements
    WorkingMemory,
    InternalWorkingMemoryActions,
    EventSupport,
    PropertyChangeListener {
    // ------------------------------------------------------------
    // Constants
    // ------------------------------------------------------------
    protected static final Class[]            ADD_REMOVE_PROPERTY_CHANGE_LISTENER_ARG_TYPES = new Class[]{PropertyChangeListener.class};

    // ------------------------------------------------------------
    // Instance members
    // ------------------------------------------------------------

    /** The arguments used when adding/removing a property change listener. */
    protected final Object[]                  addRemovePropertyChangeListenerArgs           = new Object[]{this};

    /** The actual memory for the <code>JoinNode</code>s. */
    protected final PrimitiveLongMap          nodeMemories                                  = new PrimitiveLongMap( 32,
                                                                                                                    8 );

    /** Global values which are associated with this memory. */
    protected final Map                       globals                                       = new HashMap();

    /** Object-to-handle mapping. */
    protected final Map                       assertMap;

    protected Map                             queryResults                                  = Collections.EMPTY_MAP;

    /** The eventSupport */
    protected final WorkingMemoryEventSupport workingMemoryEventSupport                     = new WorkingMemoryEventSupport( this );

    protected final AgendaEventSupport        agendaEventSupport                            = new AgendaEventSupport( this );

    /** The <code>RuleBase</code> with which this memory is associated. */
    protected transient InternalRuleBase          ruleBase;

    protected final FactHandleFactory         handleFactory;

    protected final TruthMaintenanceSystem    tms;

    /** Rule-firing agenda. */
    protected DefaultAgenda                   agenda;

    protected final List                      factQueue                                     = new ArrayList();

    protected final ReentrantLock             lock                                          = new ReentrantLock();

    protected final boolean                   discardOnLogicalOverride;

    protected long                            propagationIdCounter;

    /** Flag to determine if a rule is currently being fired. */
    protected boolean                         firing;

    // ------------------------------------------------------------
    // Constructors
    // ------------------------------------------------------------

    /**
     * Construct.
     * 
     * @param ruleBase
     *            The backing rule-base.
     */
    public AbstractWorkingMemory(final InternalRuleBase ruleBase,
                                 final FactHandleFactory handleFactory) {
        this.ruleBase = ruleBase;
        this.handleFactory = handleFactory;
        this.tms = new TruthMaintenanceSystem( this );
        final RuleBaseConfiguration conf = this.ruleBase.getConfiguration();

        if ( RuleBaseConfiguration.WM_BEHAVIOR_IDENTITY.equals( conf.getProperty( RuleBaseConfiguration.PROPERTY_ASSERT_BEHAVIOR ) ) ) {
            this.assertMap = new FastMap().setKeyComparator( new IdentityAssertMapComparator( this.handleFactory.getFactHandleType() ) );
        } else {
            this.assertMap = new FastMap().setKeyComparator( new EqualityAssertMapComparator( this.handleFactory.getFactHandleType() ) );
        }

        // Only takes effect if are using idententity behaviour for assert
        if ( RuleBaseConfiguration.WM_BEHAVIOR_DISCARD.equals( conf.getProperty( RuleBaseConfiguration.PROPERTY_LOGICAL_OVERRIDE_BEHAVIOR ) ) ) {
            this.discardOnLogicalOverride = true;
        } else {
            this.discardOnLogicalOverride = false;
        }

    }

    // ------------------------------------------------------------
    // Instance methods
    // ------------------------------------------------------------

    void setRuleBase(InternalRuleBase ruleBase) {
        this.ruleBase = ruleBase;
    }
    
    public void addEventListener(final WorkingMemoryEventListener listener) {
        this.workingMemoryEventSupport.addEventListener( listener );
    }

    public void removeEventListener(final WorkingMemoryEventListener listener) {
        this.workingMemoryEventSupport.removeEventListener( listener );
    }

    public List getWorkingMemoryEventListeners() {
        return this.workingMemoryEventSupport.getEventListeners();
    }

    public void addEventListener(final AgendaEventListener listener) {
        this.agendaEventSupport.addEventListener( listener );
    }

    public void removeEventListener(final AgendaEventListener listener) {
        this.agendaEventSupport.removeEventListener( listener );
    }

    public FactHandleFactory getFactHandleFactory() {
        return this.handleFactory;
    }

    public List getAgendaEventListeners() {
        return this.agendaEventSupport.getEventListeners();
    }

    /**
     * @see WorkingMemory
     */
    public Map getGlobals() {
        return this.globals;
    }

    /**
     * @see WorkingMemory
     */
    public void setGlobal(final String name,
                          final Object value) {
        // Make sure the global has been declared in the RuleBase
        final Map globalDefintions = this.ruleBase.getGlobals();
        final Class type = (Class) globalDefintions.get( name );
        if ( (type == null) ) {
            throw new RuntimeException( "Unexpected global [" + name + "]" );
        } else if ( !type.isInstance( value ) ) {
            throw new RuntimeException( "Illegal class for global. " + "Expected [" + type.getName() + "], " + "found [" + value.getClass().getName() + "]." );

        } else {
            this.globals.put( name,
                              value );
        }
    }

    /**
     * @see WorkingMemory
     */
    public Object getGlobal(final String name) {
        final Object object = this.globals.get( name );
        return object;
    }

    /**
     * Retrieve the rule-firing <code>Agenda</code> for this
     * <code>WorkingMemory</code>.
     * 
     * @return The <code>Agenda</code>.
     */
    public Agenda getAgenda() {
        return this.agenda;
    }

    /**
     * Clear the Agenda
     */
    public void clearAgenda() {
        this.agenda.clearAgenda();
    }

    /**
     * Clear the Agenda Group
     */
    public void clearAgendaGroup(final String group) {
        this.agenda.clearAgendaGroup( group );
    }

    /**
     * @see WorkingMemory
     */
    public RuleBase getRuleBase() {
        return this.ruleBase;
    }

    /**
     * @see WorkingMemory
     */
    public void fireAllRules() throws FactException {
        fireAllRules( null );
    }

    public synchronized void fireAllRules(final AgendaFilter agendaFilter) throws FactException {
        // If we're already firing a rule, then it'll pick up
        // the firing for any other assertObject(..) that get
        // nested inside, avoiding concurrent-modification
        // exceptions, depending on code paths of the actions.

        if ( !this.firing ) {
            try {
                this.firing = true;

                while ( this.agenda.fireNextItem( agendaFilter ) ) {
                    ;
                }
            } finally {
                this.firing = false;
            }
        }
    }

    /**
     * Returns the fact Object for the given <code>FactHandle</code>. It
     * actually attemps to return the value from the handle, before retrieving
     * it from objects map.
     * 
     * @see WorkingMemory
     * 
     * @param handle
     *            The <code>FactHandle</code> reference for the
     *            <code>Object</code> lookup
     * 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -