Java Code Examples for org.kie.api.KieBase#newStatelessKieSession()

The following examples show how to use org.kie.api.KieBase#newStatelessKieSession() . 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: RulesBasedRoutingStrategy.java    From mdw with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<String> determineWorkgroups(TaskTemplate taskTemplate, TaskInstance taskInstance) throws StrategyException {
    KieBase knowledgeBase = getKnowledgeBase();

    StatelessKieSession knowledgeSession = knowledgeBase.newStatelessKieSession();

    List<Object> facts = new ArrayList<Object>();
    facts.add(getParameters());
    knowledgeSession.setGlobal("taskTemplate", taskTemplate);
    knowledgeSession.setGlobal("taskInstance", taskInstance);
    knowledgeSession.setGlobal("now", new Date());

    knowledgeSession.execute(CommandFactory.newInsertElements(facts));

    return taskInstance.getWorkgroups();
}
 
Example 2
Source File: RulesBasedPrioritizationStrategy.java    From mdw with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Date determineDueDate(TaskTemplate taskTemplate) throws StrategyException {

    TaskInstance taskInstance = new TaskInstance();  // for holding values

    // execute rules only once (results are stored in taskInstance)
    KieBase knowledgeBase = getKnowledgeBase();
    StatelessKieSession knowledgeSession = knowledgeBase.newStatelessKieSession();

    List<Object> facts = new ArrayList<>();
    facts.add(getParameters());
    knowledgeSession.setGlobal("taskTemplate", taskTemplate);
    knowledgeSession.setGlobal("taskInstance", taskInstance);

    knowledgeSession.execute(CommandFactory.newInsertElements(facts));

    return Date.from(taskInstance.getDue());
}
 
Example 3
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public StatelessKieSession newStatelessKieSession(String kSessionName, KieSessionConfiguration conf) {
    KieSessionModelImpl kSessionModel = kSessionName != null ?
                                        (KieSessionModelImpl) getKieSessionModel(kSessionName) :
                                        (KieSessionModelImpl) findKieSessionModel(true);

    if ( kSessionModel == null ) {
        log.error("Unknown KieSession name: " + kSessionName);
        return null;
    }
    if (kSessionModel.getType() == KieSessionModel.KieSessionType.STATEFUL) {
        throw new RuntimeException("Trying to create a stateless KieSession from a stateful KieSessionModel: " + kSessionModel.getName());
    }
    KieBase kBase = getKieBase( kSessionModel.getKieBaseModel().getName() );
    if ( kBase == null ) {
        log.error("Unknown KieBase name: " + kSessionModel.getKieBaseModel().getName());
        return null;
    }

    StatelessKieSession statelessKieSession = kBase.newStatelessKieSession( conf != null ? conf : getKieSessionConfiguration( kSessionModel ) );
    if (isJndiAvailable()) {
        wireSessionComponents( kSessionModel, statelessKieSession );
    }
    registerLoggers(kSessionModel, statelessKieSession);

    ((StatelessKnowledgeSessionImpl) statelessKieSession).initMBeans(containerId, ((InternalKnowledgeBase) kBase).getId(), kSessionModel.getName());

    statelessKSessions.put(kSessionModel.getName(), statelessKieSession);
    return statelessKieSession;
}
 
Example 4
Source File: StatelessSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotInStatelessSession() throws Exception {
    final KieBaseConfiguration kbc = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbc.setOption(SequentialOption.YES);
    final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase(kbc, "test_NotInStatelessSession.drl"));
    final StatelessKieSession session = kbase.newStatelessKieSession();

    final List list = new ArrayList();
    session.setGlobal("list", list);
    session.execute("not integer");
    assertEquals("not integer", list.get(0));
}
 
Example 5
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testArrays() {
    String text = "package test_mvel;\n";
    text += "import " + TestObject.class.getCanonicalName() + ";\n";
    text += "import function " + TestObject.class.getCanonicalName() + ".array;\n";
    text += "no-loop true\n";
    text += "dialect \"mvel\"\n";
    text += "rule \"1\"\n";
    text += "salience 1\n";
    text += "when\n";
    text += "    $fact: TestObject()\n";
    text += "    eval($fact.checkHighestPriority(\"mvel\", 2))\n";
    text += "    eval($fact.stayHasDaysOfWeek(\"mvel\", false, new String[][]{{\"2008-04-01\", \"2008-04-10\"}}))\n";
    text += "then\n";
    text += "    $fact.applyValueAddPromo(1,2,3,4,\"mvel\");\n";
    text += "end";

    final KieBase kieBase = loadKnowledgeBaseFromString(text.replaceAll("mvel", "java"), text);
    final StatelessKieSession statelessKieSession = kieBase.newStatelessKieSession();

    final List<String> list = new ArrayList<String>();
    statelessKieSession.execute(new TestObject(list));

    assertEquals(6, list.size());
    assertTrue(list.containsAll( Arrays.asList("TestObject.checkHighestPriority: java|2",
                                               "TestObject.stayHasDaysOfWeek: java|false|[2008-04-01, 2008-04-10]",
                                               "TestObject.checkHighestPriority: mvel|2",
                                               "TestObject.stayHasDaysOfWeek: mvel|false|[2008-04-01, 2008-04-10]",
                                               "TestObject.applyValueAddPromo: 1|2|3|4|mvel",
                                               "TestObject.applyValueAddPromo: 1|2|3|4|java") ));
}
 
Example 6
Source File: DroolsExecutor.java    From mdw with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object execute(Asset rulesAsset, Operand input) throws ExecutionException {

    ClassLoader packageClassLoader = null;
    if (input.getContext() != null && input.getContext().getPackage() != null)
        packageClassLoader = input.getContext().getPackage().getClassLoader();
    if (packageClassLoader == null) // fall back to rules asset pkg classloader
        packageClassLoader = PackageCache.getPackage(rulesAsset.getPackageName()).getClassLoader();

    KnowledgeBaseAsset kbAsset = DroolsKnowledgeBaseCache
            .getKnowledgeBaseAsset(rulesAsset.getName(), null, packageClassLoader);
    if (kbAsset == null) {
        throw new ExecutionException("Cannot load KnowledgeBase asset: "
                + rulesAsset.getPackageName() + "/" + rulesAsset.getLabel());
    }

    KieBase knowledgeBase = kbAsset.getKnowledgeBase();

    StatelessKieSession kSession = knowledgeBase.newStatelessKieSession();

    List<Object> facts = new ArrayList<Object>();
    if (input.getInput() != null) {
        facts.add(input.getInput()); // direct access
        if (input.getInput() instanceof Jsonable)
            facts.add(((Jsonable)input.getInput()).getJson());
    }

    kSession.setGlobal("operand", input);
    kSession.execute(CommandFactory.newInsertElements(facts));
    return input.getResult();
}
 
Example 7
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
protected StatelessKieSession createStatelessKnowledgeSession(KieBase kbase) {
    return kbase.newStatelessKieSession();
}
 
Example 8
Source File: StatelessStressTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Disabled
@Test
public void testLotsOfStateless() throws Exception {
    final KieBase kbase = loadKnowledgeBase("thread_class_test.drl");

    int numThreads = 100;
    Thread[] ts = new Thread[numThreads];
    
    
        for (int i=0; i<numThreads; i++) {
            Runnable run = () -> {

                long start = 0;
                long previous = 0;

                while (true) {
                    start = System.currentTimeMillis();
                    StatelessKieSession sess = kbase.newStatelessKieSession();
                    try {
                        sess    = SerializationHelper.serializeObject(sess);
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                    Person p = new Person();
                    p.setName( "Michael" );
                    Address add1 = new Address();
                    add1.setStreet( "High" );
                    Address add2 = new Address();
                    add2.setStreet( "Low" );
                    List l = new ArrayList();
                    l.add( add1 ); l.add( add2 );
                    p.setAddresses( l );
                    sess.execute( p );

                    long current = System.currentTimeMillis() - start;
                    if (previous != 0) {
                        float f = current/previous;
                        if (f > 1) {
                            System.err.println("SLOWDOWN");
                        }
                    }

                    previous = current;
                }
            };
            
            Thread t = new Thread(run);
            t.start();
            ts[i] = t;
        }
        
        for ( int i = 0; i < ts.length; i++ ) {
            ts[i].join();
        }
    
    
    
    
}
 
Example 9
Source File: DroolsActivity.java    From mdw with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void execute() throws ActivityException {

    String knowledgeBaseName = null;
    String knowledgeBaseVersion = null;
    try {
        knowledgeBaseName = getAttributeValueSmart(KNOWLEDGE_BASE);
        knowledgeBaseVersion = getAttributeValueSmart(KNOWLEDGE_BASE_ASSET_VERSION);
    }
    catch (PropertyException ex) {
        throw new ActivityException(ex.getMessage(), ex);
    }

    if (StringUtils.isBlank(knowledgeBaseName))
        throw new ActivityException("Missing attribute: " + KNOWLEDGE_BASE);

    KieBase knowledgeBase = getKnowledgeBase(knowledgeBaseName, knowledgeBaseVersion);
    if (knowledgeBase == null)
        throw new ActivityException("Cannot load KnowledgeBase: " + knowledgeBaseName);

    // TODO stateful session option
    StatelessKieSession kSession = knowledgeBase.newStatelessKieSession();

    List<Object> facts = new ArrayList<>();
    Map<String,Object> values = new HashMap<>();

    for (VariableInstance variableInstance : getParameters()) {
        Object value = getVariableValue(variableInstance.getName());
        values.put(variableInstance.getName(), value);
    }
    logDebug("Drools values: " + values);

    facts.add(values);
    logDebug("Drools facts: " + facts);

    setGlobalValues(kSession);

    kSession.execute(CommandFactory.newInsertElements(facts));

    String temp = getAttributeValue(OUTPUTDOCS);
    setOutputDocuments(getAttributes().containsKey(OUTPUTDOCS) ? getAttributes().getList(OUTPUTDOCS).toArray(new String[0]) : new String[0]);

    // TODO handle document variables
    Process processVO = getProcessDefinition();
    for (Variable variable : processVO.getVariables()) {
        Object newValue = values.get(variable.getName());
        if (newValue != null)
            setVariableValue(variable.getName(), variable.getType(), newValue);
    }
}