Search in sources :

Example 46 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class FieldConstraintTest method testLiteralConstraint.

/**
 * <pre>
 *
 *                ( Cheese (type &quot;cheddar&quot;) )
 *
 * </pre>
 *
 * This is currently the same as using a ReturnValueConstraint just that it
 * doesn't need any requiredDeclarations
 */
@Test
public void testLiteralConstraint() {
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
    final ClassFieldReader extractor = store.getReader(Cheese.class, "type");
    final MvelConstraint constraint = new MvelConstraintTestUtil("type == \"cheddar\"", FieldFactory.getInstance().getFieldValue("cheddar"), extractor);
    final Cheese cheddar = new Cheese("cheddar", 5);
    final InternalFactHandle cheddarHandle = (InternalFactHandle) ksession.insert(cheddar);
    // check constraint
    assertTrue(constraint.isAllowed(cheddarHandle, ksession));
    final Cheese stilton = new Cheese("stilton", 5);
    final InternalFactHandle stiltonHandle = (InternalFactHandle) ksession.insert(stilton);
    // check constraint
    assertFalse(constraint.isAllowed(stiltonHandle, ksession));
}
Also used : ClassFieldReader(org.drools.core.base.ClassFieldReader) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) Cheese(org.drools.core.test.model.Cheese) InternalFactHandle(org.drools.core.common.InternalFactHandle) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 47 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class PersistableRunner method initKieSessionMBeans.

private void initKieSessionMBeans(KieSession ksession) {
    InternalKnowledgeBase internalKnowledgeBase = (InternalKnowledgeBase) ksession.getKieBase();
    StatefulKnowledgeSessionImpl statefulKnowledgeSessionImpl = (StatefulKnowledgeSessionImpl) ksession;
    // DROOLS-1322
    statefulKnowledgeSessionImpl.initMBeans(internalKnowledgeBase.getContainerId(), internalKnowledgeBase.getId(), "persistent");
}
Also used : StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase)

Example 48 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project jbpm by kiegroup.

the class MVELAction method execute.

public void execute(ProcessContext context) throws Exception {
    int length = unit.getOtherIdentifiers().length;
    Object[] vars = new Object[length];
    if (unit.getOtherIdentifiers() != null) {
        for (int i = 0; i < length; i++) {
            vars[i] = context.getVariable(unit.getOtherIdentifiers()[i]);
        }
    }
    InternalWorkingMemory internalWorkingMemory = null;
    if (context.getKieRuntime() instanceof StatefulKnowledgeSessionImpl) {
        internalWorkingMemory = ((StatefulKnowledgeSessionImpl) context.getKieRuntime()).getInternalWorkingMemory();
    } else if (context.getKieRuntime() instanceof StatelessKnowledgeSessionImpl) {
        StatefulKnowledgeSession statefulKnowledgeSession = ((StatelessKnowledgeSessionImpl) context.getKieRuntime()).newWorkingMemory();
        internalWorkingMemory = ((StatefulKnowledgeSessionImpl) statefulKnowledgeSession).getInternalWorkingMemory();
    }
    VariableResolverFactory factory = unit.getFactory(context, // No previous declarations
    null, // No rule
    null, // No "right object"
    null, // No (left) tuples
    null, vars, internalWorkingMemory, (GlobalResolver) context.getKieRuntime().getGlobals());
    // KnowledgePackage pkg = context.getKnowledgeRuntime().getKnowledgeBase().getKnowledgePackage( "MAIN" );
    // if ( pkg != null && pkg instanceof KnowledgePackageImp) {
    // MVELDialectRuntimeData data = ( MVELDialectRuntimeData ) ((KnowledgePackageImp) pkg).pkg.getDialectRuntimeRegistry().getDialectData( id );
    // factory.setNextFactory( data.getFunctionFactory() );
    // }
    // 
    MVELSafeHelper.getEvaluator().executeExpression(this.expr, null, factory);
}
Also used : InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) StatelessKnowledgeSessionImpl(org.drools.core.impl.StatelessKnowledgeSessionImpl) VariableResolverFactory(org.mvel2.integration.VariableResolverFactory) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession)

Example 49 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project jbpm by kiegroup.

the class DynamicUtils method internalAddDynamicWorkItem.

private static void internalAddDynamicWorkItem(final WorkflowProcessInstance processInstance, final DynamicNodeInstance dynamicContext, KieRuntime ksession, String workItemName, Map<String, Object> parameters) {
    final WorkItemImpl workItem = new WorkItemImpl();
    workItem.setState(WorkItem.ACTIVE);
    workItem.setProcessInstanceId(processInstance.getId());
    workItem.setDeploymentId((String) ksession.getEnvironment().get(EnvironmentName.DEPLOYMENT_ID));
    workItem.setName(workItemName);
    workItem.setParameters(parameters);
    for (Map.Entry<String, Object> entry : workItem.getParameters().entrySet()) {
        if (entry.getValue() instanceof String) {
            String s = (String) entry.getValue();
            Object variableValue = null;
            Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher(s);
            while (matcher.find()) {
                String paramName = matcher.group(1);
                variableValue = processInstance.getVariable(paramName);
                if (variableValue == null) {
                    try {
                        variableValue = MVELSafeHelper.getEvaluator().eval(paramName, new ProcessInstanceResolverFactory(processInstance));
                    } catch (Throwable t) {
                        logger.error("Could not find variable scope for variable {}", paramName);
                        logger.error("when trying to replace variable in string for Dynamic Work Item {}", workItemName);
                        logger.error("Continuing without setting parameter.");
                    }
                }
            }
            if (variableValue != null) {
                workItem.setParameter(entry.getKey(), variableValue);
            }
        }
    }
    final WorkItemNodeInstance workItemNodeInstance = new WorkItemNodeInstance();
    workItemNodeInstance.internalSetWorkItem(workItem);
    workItemNodeInstance.setMetaData("NodeType", workItemName);
    workItem.setNodeInstanceId(workItemNodeInstance.getId());
    if (ksession instanceof StatefulKnowledgeSessionImpl) {
        workItemNodeInstance.setProcessInstance(processInstance);
        workItemNodeInstance.setNodeInstanceContainer(dynamicContext == null ? processInstance : dynamicContext);
        workItemNodeInstance.addEventListeners();
        executeWorkItem((StatefulKnowledgeSessionImpl) ksession, workItem, workItemNodeInstance);
    } else if (ksession instanceof CommandBasedStatefulKnowledgeSession) {
        ExecutableRunner runner = ((CommandBasedStatefulKnowledgeSession) ksession).getRunner();
        runner.execute(new ExecutableCommand<Void>() {

            private static final long serialVersionUID = 5L;

            public Void execute(Context context) {
                StatefulKnowledgeSession ksession = (StatefulKnowledgeSession) ((RegistryContext) context).lookup(KieSession.class);
                WorkflowProcessInstance realProcessInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstance.getId());
                workItemNodeInstance.setProcessInstance(realProcessInstance);
                if (dynamicContext == null) {
                    workItemNodeInstance.setNodeInstanceContainer(realProcessInstance);
                } else {
                    DynamicNodeInstance realDynamicContext = findDynamicContext(realProcessInstance, dynamicContext.getUniqueId());
                    workItemNodeInstance.setNodeInstanceContainer(realDynamicContext);
                }
                workItemNodeInstance.addEventListeners();
                executeWorkItem((StatefulKnowledgeSessionImpl) ksession, workItem, workItemNodeInstance);
                return null;
            }
        });
    } else {
        throw new IllegalArgumentException("Unsupported ksession: " + ksession == null ? "null" : ksession.getClass().getName());
    }
}
Also used : RegistryContext(org.drools.core.command.impl.RegistryContext) Context(org.kie.api.runtime.Context) Matcher(java.util.regex.Matcher) CommandBasedStatefulKnowledgeSession(org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) CommandBasedStatefulKnowledgeSession(org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession) ExecutableRunner(org.kie.api.runtime.ExecutableRunner) ProcessInstanceResolverFactory(org.jbpm.workflow.instance.impl.ProcessInstanceResolverFactory) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) WorkItemImpl(org.drools.core.process.instance.impl.WorkItemImpl) ExecutableCommand(org.drools.core.command.impl.ExecutableCommand) KieSession(org.kie.api.runtime.KieSession) Map(java.util.Map) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance)

Example 50 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class IndexingTest method testIndexingOnQueryUnificationWithNot.

@Test(timeout = 10000)
public void testIndexingOnQueryUnificationWithNot() throws Exception {
    String str = "";
    str += "package org.drools.compiler.test  \n";
    str += "import org.drools.compiler.Person \n";
    str += "query peeps( String $name, int $age ) \n";
    str += "    not $p2 : Person( $name := name, age > $age ) \n";
    str += "end\n";
    KieBase kbase = loadKnowledgeBaseFromString(str);
    List<ObjectTypeNode> nodes = ((KnowledgeBaseImpl) kbase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for (ObjectTypeNode n : nodes) {
        if (((ClassObjectType) n.getObjectType()).getClassType() == DroolsQuery.class) {
            node = n;
            break;
        }
    }
    StatefulKnowledgeSessionImpl wm = ((StatefulKnowledgeSessionImpl) kbase.newKieSession());
    AlphaNode alphanode = (AlphaNode) node.getObjectSinkPropagator().getSinks()[0];
    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) alphanode.getObjectSinkPropagator().getSinks()[0];
    NotNode n = (NotNode) liaNode.getSinkPropagator().getSinks()[0];
    DoubleNonIndexSkipBetaConstraints c = (DoubleNonIndexSkipBetaConstraints) n.getRawConstraints();
    // assertEquals( "$name", ((VariableConstraint)c.getConstraint()).getRequiredDeclarations()[0].getIdentifier() );
    assertTrue(c.isIndexed());
    BetaMemory bm = (BetaMemory) wm.getNodeMemory(n);
    System.out.println(bm.getLeftTupleMemory().getClass());
    System.out.println(bm.getRightTupleMemory().getClass());
    assertTrue(bm.getLeftTupleMemory() instanceof TupleIndexHashTable);
    assertTrue(bm.getRightTupleMemory() instanceof TupleIndexHashTable);
    final Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("inserted", new Integer(0));
    map.put("deleted", new Integer(0));
    map.put("updated", new Integer(0));
    wm.openLiveQuery("peeps", new Object[] { Variable.v, 99 }, new ViewChangedEventListener() {

        @Override
        public void rowInserted(Row row) {
            System.out.println("inserted");
            Integer integer = map.get("inserted");
            map.put("inserted", integer.intValue() + 1);
        }

        @Override
        public void rowDeleted(Row row) {
            System.out.println("deleted");
            Integer integer = map.get("deleted");
            map.put("deleted", integer.intValue() + 1);
        }

        @Override
        public void rowUpdated(Row row) {
            System.out.println("updated");
            Integer integer = map.get("updated");
            map.put("updated", integer.intValue() + 1);
        }
    });
    System.out.println("inserted: " + map.get("inserted"));
    System.out.println("deleted: " + map.get("deleted"));
    System.out.println("updated: " + map.get("updated"));
    Map<String, InternalFactHandle> peeps = new HashMap<String, InternalFactHandle>();
    Person p = null;
    InternalFactHandle fh = null;
    int max = 3;
    // 1 matched, prior to any insertions
    assertEquals(1, map.get("inserted").intValue());
    assertEquals(0, map.get("deleted").intValue());
    assertEquals(0, map.get("updated").intValue());
    // x0 is the blocker
    for (int i = 0; i < max; i++) {
        p = new Person("x" + i, 100);
        fh = (InternalFactHandle) wm.insert(p);
        wm.fireAllRules();
        peeps.put(p.getName(), fh);
    }
    // insertions case 1 deletion
    assertEquals(1, map.get("inserted").intValue());
    assertEquals(1, map.get("deleted").intValue());
    assertEquals(0, map.get("updated").intValue());
    // each x is blocker in turn up to x99
    for (int i = 0; i < (max - 1); i++) {
        fh = peeps.get("x" + i);
        p = (Person) fh.getObject();
        p.setAge(90);
        wm.update(fh, p);
        wm.fireAllRules();
        // make sure this doesn't change
        assertEquals("i=" + i, 1, map.get("inserted").intValue());
    }
    // no change
    assertEquals(1, map.get("inserted").intValue());
    assertEquals(1, map.get("deleted").intValue());
    assertEquals(0, map.get("updated").intValue());
    // x99 is still the blocker, everything else is just added
    for (int i = 0; i < (max - 1); i++) {
        fh = peeps.get("x" + i);
        p = (Person) fh.getObject();
        p.setAge(102);
        wm.update(fh, p);
        wm.fireAllRules();
        // make sure this doesn't change
        assertEquals("i=" + i, 1, map.get("inserted").intValue());
    }
    // no change
    assertEquals(1, map.get("inserted").intValue());
    assertEquals(1, map.get("deleted").intValue());
    assertEquals(0, map.get("updated").intValue());
    // x99 is still the blocker
    for (int i = (max - 2); i >= 0; i--) {
        fh = peeps.get("x" + i);
        p = (Person) fh.getObject();
        p.setAge(90);
        wm.update(fh, p);
        wm.fireAllRules();
        // make sure this doesn't change
        assertEquals("i=" + i, 1, map.get("inserted").intValue());
    }
    // move x99, should no longer be a blocker, now it can increase
    fh = peeps.get("x" + (max - 1));
    p = (Person) fh.getObject();
    p.setAge(90);
    wm.update(fh, p);
    wm.fireAllRules();
    assertEquals(2, map.get("inserted").intValue());
}
Also used : NotNode(org.drools.core.reteoo.NotNode) HashMap(java.util.HashMap) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) BetaMemory(org.drools.core.reteoo.BetaMemory) TupleIndexHashTable(org.drools.core.util.index.TupleIndexHashTable) AlphaNode(org.drools.core.reteoo.AlphaNode) IndexableConstraint(org.drools.core.rule.IndexableConstraint) DoubleNonIndexSkipBetaConstraints(org.drools.core.common.DoubleNonIndexSkipBetaConstraints) ViewChangedEventListener(org.kie.api.runtime.rule.ViewChangedEventListener) KieBase(org.kie.api.KieBase) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) Row(org.kie.api.runtime.rule.Row) InternalFactHandle(org.drools.core.common.InternalFactHandle) Person(org.drools.compiler.Person) LeftInputAdapterNode(org.drools.core.reteoo.LeftInputAdapterNode) Test(org.junit.Test)

Aggregations

StatefulKnowledgeSessionImpl (org.drools.core.impl.StatefulKnowledgeSessionImpl)84 Test (org.junit.Test)63 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)41 KieSession (org.kie.api.runtime.KieSession)24 ArrayList (java.util.ArrayList)22 InternalFactHandle (org.drools.core.common.InternalFactHandle)22 List (java.util.List)20 DefaultFactHandle (org.drools.core.common.DefaultFactHandle)17 KieBaseConfiguration (org.kie.api.KieBaseConfiguration)17 ClassObjectType (org.drools.core.base.ClassObjectType)14 FactHandle (org.kie.api.runtime.rule.FactHandle)14 KieBase (org.kie.api.KieBase)13 HashMap (java.util.HashMap)9 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)8 LeftTupleImpl (org.drools.core.reteoo.LeftTupleImpl)8 BuildContext (org.drools.core.reteoo.builder.BuildContext)8 Cheese (org.drools.core.test.model.Cheese)8 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)7 RuleDescr (org.drools.compiler.lang.descr.RuleDescr)6 TruthMaintenanceSystem (org.drools.core.common.TruthMaintenanceSystem)6