org.kie.api.definition.rule.Rule Java Examples

The following examples show how to use org.kie.api.definition.rule.Rule. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RightInputAdapterNode.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
public boolean removeAssociation( Rule rule ) {
    boolean result = super.associations.remove(rule);
    if (getAssociationsSize() == 0) {
        // avoid to recalculate the pathEndNodes if this node is going to be removed
        return result;
    }

    List<PathEndNode> remainingPathNodes = new ArrayList<PathEndNode>();
    for (PathEndNode pathEndNode : pathEndNodes) {
        if (pathEndNode.getAssociationsSize() > 0) {
            remainingPathNodes.add(pathEndNode);
        }
    }
    pathEndNodes = remainingPathNodes.toArray( new PathEndNode[remainingPathNodes.size()] );
    return result;
}
 
Example #2
Source File: TrackingAgendaEventListener.java    From qzr with Apache License 2.0 6 votes vote down vote up
@Override
public void afterMatchFired(AfterMatchFiredEvent event) {
    Rule rule = event.getMatch().getRule();

    String ruleName = rule.getName();
    Map<String, Object> ruleMetaDataMap = rule.getMetaData();

    addActivation(new Activation(ruleName));
    StringBuilder sb = new StringBuilder("Rule fired: " + ruleName);

    if (ruleMetaDataMap.size() > 0) {
        sb.append("\n  With [" + ruleMetaDataMap.size() + "] meta-data:");
        for (String key : ruleMetaDataMap.keySet()) {
            sb.append("\n    key=" + key + ", value="
                    + ruleMetaDataMap.get(key));
        }
    }

    log.debug(sb.toString());
}
 
Example #3
Source File: AddRemoveRule.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private static PathEndNodes getPathEndNodes(InternalKnowledgeBase kBase,
                                            LeftTupleNode lt,
                                            TerminalNode tn,
                                            Rule processedRule,
                                            boolean hasProtos,
                                            boolean hasWms) {
    PathEndNodes endNodes = new PathEndNodes();
    endNodes.subjectEndNode = (PathEndNode) tn;
    endNodes.subjectEndNodes.add((PathEndNode) tn);
    if (hasWms && SegmentUtilities.isTipNode(lt, null)) {
        endNodes.subjectSplit = lt;
        endNodes.subjectSplits.add(lt);
    }

    if (hasProtos) {
        invalidateRootNode( kBase, lt );
    }

    collectPathEndNodes(kBase, lt, endNodes, tn, processedRule, hasProtos, hasWms, hasProtos && isSplit(lt));

    return endNodes;
}
 
Example #4
Source File: AddRemoveRule.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private static void insertPeerRightTuple( LeftTuple lt, InternalWorkingMemory wm, Rule rule, boolean insert ) {
    // There's a shared RightInputAdaterNode, so check if one of its sinks is associated only to the new rule
    LeftTuple prevLt = null;
    RightInputAdapterNode rian = lt.getTupleSink();

    for (ObjectSink sink : rian.getObjectSinkPropagator().getSinks()) {
        if (lt != null) {
            if (prevLt != null && !insert && sink.isAssociatedWith(rule) && sink.getAssociationsSize() == 1) {
                prevLt.setPeer( null );
            }
            prevLt = lt;
            lt = lt.getPeer();
        } else if (insert) {
            BetaMemory bm = (BetaMemory) wm.getNodeMemory( (BetaNode) sink );
            prevLt = rian.createPeer( prevLt );
            bm.linkNode( (BetaNode) sink, wm );
            bm.getStagedRightTuples().addInsert((RightTuple)prevLt);
        }
    }
}
 
Example #5
Source File: MVELSalienceExpression.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public int getValue(final KnowledgeHelper khelper,
                    final Rule rule,
                    final WorkingMemory workingMemory) {
    VariableResolverFactory factory = unit.getFactory( khelper, 
                                                       khelper != null ? ((AgendaItem)khelper.getMatch()).getTerminalNode().getSalienceDeclarations() : null, 
                                                       rule, null, 
                                                       khelper != null ? (LeftTuple) khelper.getMatch().getTuple() : null, 
                                                       null, (InternalWorkingMemory) workingMemory, workingMemory.getGlobalResolver() );
    
    // do we have any functions for this namespace?
    InternalKnowledgePackage pkg = workingMemory.getKnowledgeBase().getPackage( "MAIN" );
    if ( pkg != null ) {
        MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData( this.id );
        factory.setNextFactory( data.getFunctionFactory() );
    }

    Object value = MVEL.executeExpression( this.expr, factory );
    if (value instanceof String) {
        value = TimeUtils.parseTimeString( (String)value );
    }
    return ((Number)value).intValue();
}
 
Example #6
Source File: MVELSalienceBuilderTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public SalienceEvaluator(InternalKnowledgeBase kBase,
                         RuleBuildContext context,
                         Rule rule,
                         Salience salience,
                         Person person) {
    wm = ((StatefulKnowledgeSessionImpl)kBase.newKieSession());

    this.context = context;
    final InternalFactHandle f0 = (InternalFactHandle) wm.insert( person );
    tuple = new LeftTupleImpl( f0,
                           null,
                           true );
    this.salience = salience;
    this.halt = false;
    this.error = false;
    this.result = (person.getAge() + 20) / 2;
    
    RuleTerminalNode rtn = new RuleTerminalNode();
    rtn.setSalienceDeclarations( context.getDeclarationResolver().getDeclarations( context.getRule() ).values().toArray( new Declaration[1] ) );
    item = new AgendaItemImpl(0, tuple, 0, null, rtn, null);
}
 
Example #7
Source File: DroolsUtil.java    From qzr with Apache License 2.0 6 votes vote down vote up
/**
 * Return a string containing the packages used to build the knowledge base.
 */
public static String knowledgeBaseDetails(KieBase kbase) {
    if (kbase == null) {
        return "Knowledge Base is null.";
    } else {
        StringBuilder sb = new StringBuilder(
                "Knowledge base built from the following packages:");
        Collection<KiePackage> packages = kbase
                .getKiePackages();
        for (KiePackage kp : packages) {
            sb.append("\n    Package: [" + kp.getName() + "]");
            for (Rule rule : kp.getRules()) {
                sb.append("\n        Rule: [" + rule.getName() + "]");
            }
        }
        return sb.toString();
    }
}
 
Example #8
Source File: RulesConfiguration.java    From cia with Apache License 2.0 6 votes vote down vote up
/**
 * Kie container.
 *
 * @return the kie container
 */
@Bean
public KieContainer kieContainer() {
	final KieServices kieServices = KieServices.Factory.get();

	final KieContainer kContainer = kieServices.getKieClasspathContainer();
	LOGGER.info("Using classloader {}, parent {}",kContainer.getClassLoader(),kContainer.getClassLoader().getParent());
	
	final Results verifyResults = kContainer.verify();
	for (final Message m : verifyResults.getMessages()) {
		LOGGER.warn("Kie container message: {}", m);
	}

	final KieBase kieBase = kContainer.getKieBase();
	for (final KiePackage kp : kieBase.getKiePackages()) {
		for (final Rule rule : kp.getRules()) {
			LOGGER.info("Loadded Rule: {} {}", kp, rule.getName());
		}
	}
	

	return kContainer;
}
 
Example #9
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public Rule getRule(Collection<Rule> rules, String name) {
    for ( Rule rule : rules ) {
        if ( rule.getName().equals( name ) ) {
            return rule;
        }
    }
    return null;
}
 
Example #10
Source File: BaseNode.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * All nodes have a unique id, set in the constructor.
 *
 * @param id
 *      The unique id
 */
public BaseNode(final int id,
                final RuleBasePartitionId partitionId,
                final boolean partitionsEnabled) {
    super();
    this.id = id;
    this.partitionId = partitionId;
    this.partitionsEnabled = partitionsEnabled;
    this.associations = new Bag<Rule>();
}
 
Example #11
Source File: DroolsUtil.java    From qzr with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @return A String detailing the packages and rules in this knowledge base.
 */
public static String kbaseDetails(KieBase kbase) {
    StringBuilder sb = new StringBuilder();
    for (KiePackage p : kbase.getKiePackages()) {
        sb.append("\n  Package : " + p.getName());
        for (Rule r : p.getRules()) {
            sb.append("\n    Rule: " + r.getName());
        }
    }
    return "Knowledge base built with packages: " + sb.toString();
}
 
Example #12
Source File: EvalConditionNode.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public boolean removeAssociation( Rule rule ) {
    boolean result = super.removeAssociation(rule);
    if (!isAssociatedWith( rule )) {
        componentsMap.remove( rule );
    }
    return result;
}
 
Example #13
Source File: LoggingAgendaEventListener.java    From qzr with Apache License 2.0 5 votes vote down vote up
@Override
public void afterMatchFired(AfterMatchFiredEvent event) {
    Rule rule = event.getMatch().getRule();

    StringBuilder sb = new StringBuilder("Rule fired: " + rule.getName());

    log.debug(sb.toString());
}
 
Example #14
Source File: ReteooBuilder.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void removeNodeAssociation(BaseNode node, Rule rule, Set<Integer> removedNodes) {
    if (node == null || !removedNodes.add( node.getId() ) || !node.removeAssociation( rule )) {
        return;
    }
    if (node instanceof LeftTupleNode) {
        removeNodeAssociation( ((LeftTupleNode)node).getLeftTupleSource(), rule, removedNodes );
    }
    if ( NodeTypeEnums.isBetaNode( node ) ) {
        removeNodeAssociation( ((BetaNode) node).getRightInput(), rule, removedNodes );
    } else if ( node.getType() == NodeTypeEnums.LeftInputAdapterNode ) {
        removeNodeAssociation( ((LeftInputAdapterNode) node).getObjectSource(), rule, removedNodes );
    } else if ( node.getType() == NodeTypeEnums.AlphaNode ) {
        removeNodeAssociation( ((AlphaNode) node).getParentObjectSource(), rule, removedNodes );
    }
}
 
Example #15
Source File: EvalConditionNode.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public void readExternal(ObjectInput in) throws IOException,
                                        ClassNotFoundException {
    super.readExternal( in );
    condition = (EvalCondition) in.readObject();
    tupleMemoryEnabled = in.readBoolean();
    componentsMap = (Map<Rule, RuleComponent>) in.readObject();
}
 
Example #16
Source File: AddRemoveRule.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private static void visitChild(InternalWorkingMemory wm, boolean insert, Rule rule, FastIterator it, Tuple lt) {
    for (; lt != null; lt = (LeftTuple) it.next(lt)) {
        LeftTuple childLt = lt.getFirstChild();
        while (childLt != null) {
            LeftTuple nextLt = childLt.getHandleNext();
            visitChild(childLt, insert, wm, rule);
            childLt = nextLt;
        }
    }
}
 
Example #17
Source File: PhreakTimerNode.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public void execute( final InternalWorkingMemory wm, boolean needEvaluation ) {
    TupleList leftTuples = timerJobCtx.getTimerNodeMemory().getInsertOrUpdateLeftTuples();
    Tuple lt = timerJobCtx.getTuple();

    if ( log.isTraceEnabled() ) {
        log.trace( "Timer Executor {} {}", timerJobCtx.getTrigger(), lt );
    }

    if ( timerJobCtx.getJobHandle().isCancel() ) {
        // this is to force a sync point, as during update propagate it can cancel the FH
        // we cannot have an update processed at the same timer is firing
        return;
    }
    if ( lt.getMemory() == null ) {
        // don't add it, if it's already added, which could happen with interval or cron timers
        leftTuples.add( lt );
    }

    timerJobCtx.getTimerNodeMemory().setNodeDirtyWithoutNotify();

    TimedRuleExecutionFilter filter = wm.getSessionConfiguration().getTimedRuleExecutionFilter();
    needEvaluation &= filter != null;

    for (final PathMemory pmem : timerJobCtx.getPathMemories()) {
        if (pmem.getPathEndNode().getAssociatedRuleSize() == 0) {
            // if the corresponding rule has been removed avoid to link and notify this pmem
            continue;
        }
        InternalAgenda agenda = pmem.getActualAgenda( wm );
        pmem.doLinkRule( agenda );

        if (needEvaluation && filter.accept(new Rule[]{pmem.getRule()})) {
            evaluateAndFireRule( pmem, agenda );
        }
    }
}
 
Example #18
Source File: PublishingAgendaEventListener.java    From qzr with Apache License 2.0 5 votes vote down vote up
/**
 * Whenever a rule's LHS matches and causes the rule to activate, this
 * method will publish the name of that rule to the Stomp message broker,
 * using the {@link SimpMessagingTemplate}.
 */
@Override
public void afterMatchFired(AfterMatchFiredEvent event) {
    Rule rule = event.getMatch().getRule();

    System.out.println("Publishing: " + rule.getName());

    AgendaEventMessage msg = new AgendaEventMessage(rule.getName());

    this.template.convertAndSend("/queue/agendaevents/", msg);
}
 
Example #19
Source File: ConsequenceException.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public String getMessage() {
    StringBuilder sb = new StringBuilder( "Exception executing consequence for " );
    Rule rule = null;

    if( match != null && ( rule = match.getRule() ) != null ){
        String packageName = rule.getPackageName();
        String ruleName = rule.getName();
        sb.append( "rule \"" ).append( ruleName ).append( "\" in " ).append( packageName );
    } else {
        sb.append( "rule, name unknown" );
    }
    sb.append( ": " ).append( super.getMessage() );
    return sb.toString();
}
 
Example #20
Source File: ReteooBuilderPerformanceTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private static void addRules(InternalKnowledgePackage pkg) {
    ReteooBuilder[]  reteBuilders   = getReteBuilders(RETEBUILDER_COUNT);

    System.out.println("Adding rules to ReteBuilder");
    long    start   = System.currentTimeMillis();
    for (ReteooBuilder reteBuilder : reteBuilders) {
        for (Rule rule : pkg.getRules())
            reteBuilder.addRule((RuleImpl)rule);
    }
    System.out.println("Added "+RULE_COUNT+" rules to each ReteBuilder's in "+
                       format(System.currentTimeMillis()-start));
}
 
Example #21
Source File: BuildUtils.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private boolean areNodesCompatibleForSharing(BuildContext context, BaseNode node, BaseNode candidate) {
    if ( node.getType() == NodeTypeEnums.RightInputAdaterNode ) {
        // avoid subnetworks sharing when they belong to 2 different agenda-groups
        String agendaGroup = context.getRule().getAgendaGroup();
        for (Rule associatedRule : node.getAssociatedRules()) {
            if (!agendaGroup.equals( (( RuleImpl ) associatedRule).getAgendaGroup() )) {
                return false;
            }
        }
    }
    return true;
}
 
Example #22
Source File: DroolsTestUtil.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static Map<String, Rule> rulestoMap( Collection<Rule> rules ) {
    Map<String, Rule> ret = new HashMap<String, Rule>();
    for ( Rule rule : rules ) {
        ret.put( rule.getName(), rule );
    }
    return ret;
}
 
Example #23
Source File: KieBaseIncludesTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method which determines the number of rules in the {@link KieBase}.
 *
 * @param kieBase
 *            the {@link KieBase}
 * @return the number of rules in the {@link KieBase}
 */
private static long getNumberOfRules(KieBase kieBase) {
    long nrOfRules = 0;

    Collection<KiePackage> kiePackages = kieBase.getKiePackages();
    for (KiePackage nextKiePackage : kiePackages) {
        Collection<Rule> rules = nextKiePackage.getRules();
        System.out.println(rules);
        nrOfRules += rules.size();
    }
    return nrOfRules;
}
 
Example #24
Source File: ActivationIteratorTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testFilteredEagerEvaluation() throws Exception {
    String str =
            "package org.simple \n" +
            "rule xxx @Propagation(EAGER) \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n" +
            "rule yyy @Propagation(EAGER) \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n";

    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption( new ForceEagerActivationOption.FILTERED( new ForceEagerActivationFilter() {
        @Override
        public boolean accept(Rule rule) {
            return rule.getName().equals("xxx");
        }
    }));

    KieBase kbase = loadKnowledgeBaseFromString(str);
    KieSession ksession = createKnowledgeSession(kbase, conf);

    final List list = new ArrayList();

    AgendaEventListener agendaEventListener = new DefaultAgendaEventListener() {
        public void matchCreated(org.kie.api.event.rule.MatchCreatedEvent event) {
            list.add("activated");
        }
    };
    ksession.addEventListener(agendaEventListener);

    ksession.insert("test");
    ((InternalWorkingMemory) ksession).flushPropagations();

    assertEquals(1, list.size());
}
 
Example #25
Source File: DroolsTestUtil.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static Map<String, Rule> rulestoMap( KieBase kbase ) {
    List<Rule> rules = new ArrayList();
    for ( KiePackage pkg : ((KnowledgeBaseImpl)kbase).getPackages() ) {
        for ( Rule rule : pkg.getRules() ) {
            rules.add(rule);
        }
    }

    return rulestoMap( rules );
}
 
Example #26
Source File: MVELCompilationUnit.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public VariableResolverFactory getFactory(final Object knowledgeHelper,
                                          final Declaration[] prevDecl,
                                          final Rule rule,
                                          final Tuple tuples,
                                          final Object[] otherVars,
                                          final InternalWorkingMemory workingMemory,
                                          final GlobalResolver globals) {
    VariableResolverFactory factory = createFactory();
    updateFactory(knowledgeHelper, prevDecl, rule, null, knowledgeHelper, tuples, otherVars, workingMemory, globals, factory );
    return factory;
}
 
Example #27
Source File: MVELCompilationUnit.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public VariableResolverFactory getFactory(final Object knowledgeHelper,
                                          final Declaration[] prevDecl,
                                          final Rule rule,
                                          final InternalFactHandle rightHandle,
                                          final Tuple tuple,
                                          final Object[] otherVars,
                                          final InternalWorkingMemory workingMemory,
                                          final GlobalResolver globals) {
    VariableResolverFactory factory = createFactory();
    updateFactory(knowledgeHelper, prevDecl, rule, rightHandle, rightHandle != null ? rightHandle.getObject() : null, tuple, otherVars, workingMemory, globals, factory);
    return factory;
}
 
Example #28
Source File: TestingEventListener.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void record(Rule rule, Map<String, Integer> counts) {
    this.totalFires++;
    String name = rule.getName();
    if (!counts.containsKey(name)) {
        counts.put(name, 1);
    } else {
        counts.put(name, counts.get(name) + 1);
    }
}
 
Example #29
Source File: BaseNode.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public Rule[] getAssociatedRules() {
    return this.associations.toArray( new Rule[this.associations.getKeySize()] );
}
 
Example #30
Source File: SerializedRule.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public SerializedRule(Rule rule) {
    this.name = rule.getName();
    this.packageName = rule.getPackageName();
    this.metaAttributes = new HashMap<String, Object>( rule.getMetaData() );
}