org.drools.core.impl.InternalKnowledgeBase Java Examples

The following examples show how to use org.drools.core.impl.InternalKnowledgeBase. 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: I18nTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewClassPathResource() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    // newClassPathResource without specifying encoding
    kbuilder.add( ResourceFactory.newClassPathResource( "test_I18nPerson_utf8_forTestNewClassPathResource.drl", getClass() ),
                  ResourceType.DRL );
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession ksession = createKnowledgeSession(kbase);

    List list = new ArrayList();
    ksession.setGlobal( "list", list );

    I18nPerson i18nPerson = new I18nPerson();
    i18nPerson.set名称("山田花子");
    ksession.insert(i18nPerson);
    ksession.fireAllRules();

    assertTrue(list.contains("名称は山田花子です"));

    ksession.dispose();
}
 
Example #2
Source File: KieBaseUpdateContext.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public KieBaseUpdateContext( KieProject kProject, InternalKnowledgeBase kBase, InternalKieModule currentKM,
                             InternalKieModule newKM, KieJarChangeSet cs, Collection<Class<?>> modifiedClasses,
                             boolean modifyingUsedClass, Collection<String> unchangedResources, ResultsImpl results,
                             KieBaseModelImpl newKieBaseModel, KieBaseModelImpl currentKieBaseModel ) {
    this.kProject = kProject;
    this.kBase = kBase;
    this.currentKM = currentKM;
    this.newReleaseId = newKM.getReleaseId();
    this.newKM = newKM;
    this.cs = cs;
    this.modifiedClasses = modifiedClasses;
    this.modifyingUsedClass = modifyingUsedClass;
    this.unchangedResources = unchangedResources;
    this.results = results;
    this.newKieBaseModel = newKieBaseModel;
    this.currentKieBaseModel = currentKieBaseModel;
}
 
Example #3
Source File: StandaloneBPMNProcessTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallActivity() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("BPMN2-CallActivity.bpmn2"), ResourceType.BPMN2);
    kbuilder.add(ResourceFactory.newClassPathResource("BPMN2-CallActivitySubProcess.bpmn2"), ResourceType.BPMN2);
    if (!kbuilder.getErrors().isEmpty()) {
        for (KnowledgeBuilderError error : kbuilder.getErrors()) {
            logger.error("{}", error);
        }
        throw new IllegalArgumentException("Errors while parsing knowledge base");
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSession ksession = createKnowledgeSession(kbase);
    
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("x", "oldValue");
    ProcessInstance processInstance = ksession.startProcess("ParentProcess", params);
    assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_COMPLETED);
    assertThat(((WorkflowProcessInstance) processInstance).getVariable("y")).isEqualTo("new value");
}
 
Example #4
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 #5
Source File: ReteooWorkingMemoryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testGlobalResolver() {
    final Map<String, Object> map = new HashMap<String, Object>();
    map.put( "global1",
             "value1" );
    map.put( "global2",
             "value2" );
    final GlobalResolver resolver = new MapGlobalResolver(map);

    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kBase.newKieSession();

    ksession.setGlobalResolver( resolver );
    assertEquals( "value1",
                  ksession.getGlobal( "global1" ) );
    assertEquals( "value2",
                  ksession.getGlobal( "global2" ) );
}
 
Example #6
Source File: DynamicRulesTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testDynamicRules() throws Exception {
    InternalKnowledgeBase kbase = (InternalKnowledgeBase) loadKnowledgeBase();
    KieSession session = createKnowledgeSession(kbase);
    final Cheese a = new Cheese( "stilton",
                                 10 );
    final Cheese b = new Cheese( "stilton",
                                 15 );
    final Cheese c = new Cheese( "stilton",
                                 20 );
    session.insert( a );
    session.insert( b );
    session.insert(c);

    Collection<KiePackage> kpkgs = SerializationHelper.serializeObject( loadKnowledgePackages(  "test_DynamicRules.drl" ) );
    kbase.addPackages(kpkgs);
    kbase = SerializationHelper.serializeObject( kbase );

    session = SerializationHelper.getSerialisedStatefulKnowledgeSession( session, 
                                                                         true );

    session.fireAllRules();
}
 
Example #7
Source File: DefeasibilityTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSession( String ruleFile ) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    try {
        System.setProperty("drools.negatable", "on");
        kBuilder.add(ResourceFactory.newClassPathResource(ruleFile),
                     ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
            fail();
        }
    } finally {
        System.setProperty("drools.negatable", "off");
    }

    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
    kBase.addPackages( kBuilder.getKnowledgePackages() );


    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.DEFEASIBLE );

    KieSession kSession = kBase.newKieSession( ksConf, null );
    return kSession;
}
 
Example #8
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public KieSession newKieSession(String kSessionName, Environment environment, KieSessionConfiguration conf) {
    KieSessionModelImpl kSessionModel = kSessionName != null ?
                                        (KieSessionModelImpl) getKieSessionModel(kSessionName) :
                                        (KieSessionModelImpl) findKieSessionModel(false);

    if ( kSessionModel == null ) {
        log.error("Unknown KieSession name: " + kSessionName);
        return null;
    }

    KieBase kBase = getKieBaseFromKieSessionModel( kSessionModel );
    if ( kBase == null ) return null;

    KieSession kSession = kBase.newKieSession( conf != null ? conf : getKieSessionConfiguration( kSessionModel ), environment );
    registerNewKieSession( kSessionModel, ( InternalKnowledgeBase ) kBase, kSession );
    return kSession;
}
 
Example #9
Source File: ChangeSetTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testIntegregation() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource("changeset1Test.xml",
            getClass()),
                  ResourceType.CHANGE_SET );
    assertFalse( kbuilder.hasErrors() );
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal( "list",
                        list );
    ksession.fireAllRules();
    ksession.dispose();

    assertEquals( 2,
                  list.size() );
    assertTrue( list.containsAll( Arrays.asList( new String[]{"rule1", "rule2"} ) ) );
}
 
Example #10
Source File: AccumulateNode.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void addAccFunctionDeclarationsToLeftMask( InternalKnowledgeBase kbase, LeftTupleSource leftInput, Accumulate accumulate ) {
    BitMask leftMask = getLeftInferredMask();
    ObjectType leftObjectType = leftInput.getObjectType();
    if (leftObjectType instanceof ClassObjectType ) {
        TypeDeclaration typeDeclaration = kbase.getExactTypeDeclaration( ((ClassObjectType) leftObjectType).getClassType() );
        if (typeDeclaration != null && typeDeclaration.isPropertyReactive()) {
            List<String> accessibleProperties = typeDeclaration.getAccessibleProperties();
            for ( Declaration decl : accumulate.getRequiredDeclarations() ) {
                if ( leftObjectType.equals( decl.getPattern().getObjectType() ) ) {
                    leftMask = leftMask.setAll( decl.getPattern().getPositiveWatchMask(accessibleProperties) );
                }
            }
        }
    }
    setLeftInferredMask( leftMask );
}
 
Example #11
Source File: RuleUnlinkingWithSegmentMemoryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuleSegmentsAllLinkedTestMasks() {
    setUp( JOIN_NODE );

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    StatefulKnowledgeSessionImpl wm = new StatefulKnowledgeSessionImpl( 1L, kBase );
    
    PathMemory rs = (PathMemory) wm.getNodeMemory( rtn1 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 1, rs.getAllLinkedMaskTest() );
    
    rs = (PathMemory) wm.getNodeMemory( rtn2 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 3, rs.getAllLinkedMaskTest() );
    
    rs = (PathMemory) wm.getNodeMemory( rtn3 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 7, rs.getAllLinkedMaskTest() );
}
 
Example #12
Source File: ClassObjectTypeConf.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public ClassObjectTypeConf(final EntryPointId entryPoint,
                           final Class< ? > clazz,
                           final InternalKnowledgeBase kBase) {
    this.cls = (Activation.class.isAssignableFrom( clazz ) ) ? ClassObjectType.Match_ObjectType.getClassType() : clazz;
    this.kBase = kBase;
    this.entryPoint = entryPoint;

    this.typeDecl = kBase.getTypeDeclaration( clazz );
    if (typeDecl != null) {
        isEvent = typeDecl.getRole() == Role.Type.EVENT;
        if (isEvent) {
            expirationOffset = typeDecl.getExpirationOffset();
        }
    } else {
        Role role = clazz.getAnnotation(Role.class);
        if (role != null) {
            isEvent = role.value() == Type.EVENT;
            if (isEvent) {
                Expires expires = clazz.getAnnotation(Expires.class);
                if (expires != null) {
                    expirationOffset = TimeIntervalParser.parseSingle( expires.value() );
                }
            }
        }
    }

    isTrait = determineTraitStatus();

    this.objectType = kBase.getClassFieldAccessorCache().getClassObjectType( new ClassObjectType( clazz, isEvent ), false );

    this.concreteObjectTypeNode = kBase.getRete().getObjectTypeNodes( entryPoint ).get( objectType );

    Traitable ttbl = cls.getAnnotation( Traitable.class );
    this.traitTmsEnabled = ttbl != null && ttbl.logical();
}
 
Example #13
Source File: DynamicRulesTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemovePackage() throws Exception {
    Collection<KiePackage> kpkgs = SerializationHelper.serializeObject(loadKnowledgePackages("test_RemovePackage.drl"));
    final String packageName = kpkgs.iterator().next().getName();
    InternalKnowledgeBase kbase = (InternalKnowledgeBase) loadKnowledgeBase( );

    kbase.addPackages( kpkgs );
    kbase = SerializationHelper.serializeObject( kbase );

    KieSession session = createKnowledgeSession( kbase );

    session.insert( new Precondition( "genericcode",
                                      "genericvalue" ) );
    session.fireAllRules();

    InternalKnowledgeBase ruleBaseWM = (InternalKnowledgeBase) session.getKieBase();
    ruleBaseWM.removeKiePackage( packageName );
    
    kpkgs = SerializationHelper.serializeObject( loadKnowledgePackages(  "test_RemovePackage.drl" ) );
    ruleBaseWM.addPackages( kpkgs );
    ruleBaseWM = SerializationHelper.serializeObject( ruleBaseWM );

    session = SerializationHelper.getSerialisedStatefulKnowledgeSession( session, 
                                                                         true );
    session.fireAllRules();

    ruleBaseWM.removeKiePackage(packageName);
    ruleBaseWM.addPackages( SerializationHelper.serializeObject( kpkgs ) );

    ruleBaseWM.removeKiePackage( packageName );
    ruleBaseWM.addPackages(SerializationHelper.serializeObject(kpkgs));
}
 
Example #14
Source File: JavaDialectBinaryEqualityTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KiePackage getKnowledgePackage1() {
  
    String str = "";
    str += "package org.drools.compiler.test\n";
    str += "import " + Person.class.getName() + ";\n";
    str += "global java.util.List list\n";
    str += "rule rule1 dialect\"java\" \n";
    str += "when\n";
    str += "   $p : Person( age : age == ( 17 + 17 ), eval( age == 34 ))\n";
    str += "   eval( $p.getAge() == 34 )\n";
    str += "then\n";
    str += "   list.add( $p );\n";
    str += "end\n";
    
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ), ResourceType.DRL );
    
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
    
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    
    List<Person> list = new ArrayList<Person>();
    KieSession ksession = kbase.newKieSession();
    ksession.setGlobal( "list", list );
    ksession.insert( new Person("darth", 34) );
    ksession.fireAllRules();
    
    assertEquals( new Person( "darth", 34 ), list.get( 0 ) );
    
    return kbase.getPackage( "org.drools.compiler.test" );
}
 
Example #15
Source File: LazyTMSEnablingTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    ksession = (StatefulKnowledgeSessionImpl)kBase.newKieSession();

    tms = ((NamedEntryPoint)ksession.getWorkingMemoryEntryPoint( EntryPointId.DEFAULT.getEntryPointId() ) ).getTruthMaintenanceSystem();

}
 
Example #16
Source File: Library.java    From rhpam-7-openshift-image with Apache License 2.0 5 votes vote down vote up
public synchronized Library init(KieContext kcontext) {
    if (emf == null) {
        final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        try {
            // https://issues.jboss.org/browse/DROOLS-1108
            ClassLoader cl = ((InternalKnowledgeBase) kcontext.getKieRuntime().getKieBase()).getRootClassLoader();
            Thread.currentThread().setContextClassLoader(cl);
            emf = Persistence.createEntityManagerFactory("library");
        } finally {
            Thread.currentThread().setContextClassLoader(tccl);
        }
        new Init(emf).transact();
    }
    return this;
}
 
Example #17
Source File: KnowledgeBaseEvent.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KnowledgeBaseEvent(final InternalKnowledgeBase kBase) {
    super( kBase );
    this.kBase = kBase;
    this.pkg = null;
    this.rule = null;
    this.function = null;
}
 
Example #18
Source File: ClassObjectTypeConf.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public void readExternal(ObjectInput stream) throws IOException,
                                            ClassNotFoundException {
    kBase = (InternalKnowledgeBase) stream.readObject();
    cls = (Class<?>) stream.readObject();
    objectTypeNodes = (ObjectTypeNode[]) stream.readObject();
    objectType = (ObjectType) stream.readObject();
    concreteObjectTypeNode = (ObjectTypeNode) stream.readObject();
    entryPoint = (EntryPointId) stream.readObject();
    tmsEnabled = stream.readBoolean();
    traitTmsEnabled = stream.readBoolean();
    isEvent = stream.readBoolean();
    isTrait = stream.readBoolean();
    expirationOffset = stream.readLong();
}
 
Example #19
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public void generateCompiledAlphaNetwork(KieBaseModelImpl kBaseModel, InternalKieModule kModule, InternalKnowledgeBase kBase) {
    final String configurationProperty = kBaseModel.getKModule().getConfigurationProperty(ALPHA_NETWORK_COMPILER_OPTION);
    final Boolean isAlphaNetworkEnabled = Boolean.valueOf(configurationProperty);
    if (isAlphaNetworkEnabled) {
        KnowledgeBuilder kbuilder = kModule.getKnowledgeBuilderForKieBase(kBaseModel.getName());
        kBase.getRete().getEntryPointNodes().values().stream()
                .flatMap(ep -> ep.getObjectTypeNodes().values().stream())
                .filter(f -> !InitialFact.class.isAssignableFrom(f.getObjectType().getClassType()))
                .forEach(otn -> otn.setCompiledNetwork(ObjectTypeNodeCompiler.compile(((KnowledgeBuilderImpl) kbuilder), otn)));
    }
}
 
Example #20
Source File: InjectionHelper.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static void wireSessionComponents(BeanCreator beanCreator, KieSessionModel model, KieSession kSession) {
    BeanCreator fallbackBeanCreator = new ReflectionBeanCreator();
    ClassLoader cl = ((InternalKnowledgeBase)kSession.getKieBase()).getRootClassLoader();
    wireListeners(beanCreator, fallbackBeanCreator, cl, model.getListenerModels(), kSession);
    wireWIHs(beanCreator, fallbackBeanCreator, cl, model.getWorkItemHandlerModels(), kSession);
    wireChannels(beanCreator, fallbackBeanCreator, cl, model.getChannelModels(), kSession);
}
 
Example #21
Source File: MBeansMonitoringTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventOffset() throws Exception {
	String drl = "package org.drools.compiler.test\n" +
			"import org.drools.compiler.StockTick\n" +
			"declare StockTick\n" +
			"    @role(event)\n" +
			"    @expires(10s)\n" +
			"end\n" +
			"rule X\n" +
			"when\n" +
			"    StockTick()\n" +
			"then\n" +
			"end";

	KieServices ks = KieServices.Factory.get();

	KieModuleModel kproj = ks.newKieModuleModel();

	KieBaseModel kieBaseModel1 = kproj.newKieBaseModel( KBASE1 ).setDefault( true )
			.setEventProcessingMode( EventProcessingOption.STREAM );
	KieSessionModel ksession1 = kieBaseModel1.newKieSessionModel( KSESSION1 ).setDefault( true )
			.setType( KieSessionModel.KieSessionType.STATEFUL )
			.setClockType( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );

	ReleaseId releaseId1 = ks.newReleaseId( "org.kie.test", "mbeans", "1.0.0" );
	createKJar( ks, kproj, releaseId1, null, drl );

	KieContainer kc = ks.newKieContainer( releaseId1 );

	KieBase kiebase = kc.getKieBase( KBASE1 );
	MBeanServer mbserver = ManagementFactory.getPlatformMBeanServer();

	ObjectName kbOn = DroolsManagementAgent.createObjectNameFor((InternalKnowledgeBase) kiebase);
	mbserver.invoke( kbOn, "startInternalMBeans", new Object[0], new String[0] );

	Object expOffset = mbserver.getAttribute( new ObjectName( kbOn + ",group=EntryPoints,EntryPoint=DEFAULT,ObjectType=org.drools.compiler.StockTick" ), "ExpirationOffset" );
	assertEquals( 10001, ((Number) expOffset).longValue() );
}
 
Example #22
Source File: IntegrationInterfacesTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieBase getKnowledgeBase(final KnowledgeBuilder kbuilder) throws IOException,
                                                                       ClassNotFoundException {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    kbase = SerializationHelper.serializeObject( kbase );
    return kbase;
}
 
Example #23
Source File: PositionalTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPositional() {

    String drl =
            "import " + Man.class.getCanonicalName() + ";\n" +
            "\n" +
            "global java.util.List list;" +
            "\n" +
            "rule \"To be or not to be\"\n" +
            "when\n" +
            "    $m : Man( \"john\" , 18 , $w ; )\n" +
            "then\n" +
            "    list.add($w); " +
            "end";

    KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    knowledgeBuilder.add( new ByteArrayResource( drl.getBytes() ),
                          ResourceType.DRL );

    System.out.println( knowledgeBuilder.getErrors().toString() );
    
    assertFalse( knowledgeBuilder.hasErrors() );
    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
    kBase.addPackages( knowledgeBuilder.getKnowledgePackages() );
    KieSession kSession = createKnowledgeSession(kBase);

    java.util.ArrayList list = new ArrayList();
    kSession.setGlobal( "list",
                        list );

    kSession.insert( new Man( "john",
                              18,
                              84.2 ) );
    kSession.fireAllRules();

    assertTrue( list.contains( 84.2 ) );

}
 
Example #24
Source File: FactTemplateTypeConf.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public void readExternal(ObjectInput in) throws IOException,
                                        ClassNotFoundException {
    kBase = (InternalKnowledgeBase) in.readObject();
    factTemplate = (FactTemplate) in.readObject();
    concreteObjectTypeNode = (ObjectTypeNode) in.readObject();
    cache = (ObjectTypeNode[]) in.readObject();
    objectType = (ObjectType) in.readObject();
}
 
Example #25
Source File: DynamicRuleRemovalTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDynamicRuleRemoval() throws Exception {
    InternalKnowledgeBase kbase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    addRule(kbase, "rule1");
    addRule(kbase, "rule2");
    addRule(kbase, "rule3");

    final KieSession ksession = kbase.newKieSession();
    List<String> rulesList = new ArrayList<String>();
    ksession.setGlobal("list", rulesList);

    ksession.insert("2");
    ksession.fireAllRules();
    assertEquals(3, rulesList.size());
    assertTrue(rulesList.contains("rule1"));
    assertTrue(rulesList.contains("rule2"));
    assertTrue(rulesList.contains("rule3"));

    removeRule(kbase, "rule1");

    rulesList.clear();
    ksession.insert("3");
    ksession.fireAllRules();
    assertEquals(2, rulesList.size());
    assertFalse(rulesList.contains("rule1"));
    assertTrue(rulesList.contains("rule2"));
    assertTrue(rulesList.contains("rule3"));
}
 
Example #26
Source File: LogicalTraitTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@ParameterizedLogicalTraitTest
public void testShadowAlias(VirtualPropertyMode mode) {

    KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilderImpl.add(
            ResourceFactory.newClassPathResource("org/drools/compiler/factmodel/traits/testTraitedAliasing.drl"),
            ResourceType.DRL);
    if (kbuilderImpl.hasErrors()) {
        fail(kbuilderImpl.getErrors().toString());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilderImpl.getKnowledgePackages());

    TraitFactory.setMode(mode, kbase);

    KieSession ks = kbase.newKieSession();

    ArrayList list = new ArrayList();
    ks.setGlobal("list", list);

    ks.fireAllRules();

    for (Object o : ks.getObjects()) {
        System.out.println(o);
    }

    try {
        ks = SerializationHelper.getSerialisedStatefulKnowledgeSession(ks, true);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    System.out.println(list);
    assertFalse(list.contains(false));
    assertEquals(8, list.size());
}
 
Example #27
Source File: AddRuleTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPopulatedSharedToRtn() throws Exception {
    InternalKnowledgeBase kbase1 = buildKnowledgeBase("r1", "   A() B() C() D() E()\n");
    InternalWorkingMemory wm = ((InternalWorkingMemory)kbase1.newKieSession());
    List list = new ArrayList();
    wm.setGlobal("list", list);

    wm.insert(new A(1));
    wm.insert(new A(2));
    wm.insert(new B(1));
    wm.insert(new C(1));
    wm.insert(new D(1));
    wm.insert(new E(1));

    wm.fireAllRules();
    assertEquals( 2, list.size() );

    kbase1.addPackages( buildKnowledgePackage("r2", "   A() B() C() D() E()\n") );

    ObjectTypeNode eotn = getObjectTypeNode(kbase1, E.class );
    JoinNode eNode = (JoinNode) eotn.getObjectSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn = ( RuleTerminalNode ) eNode.getSinkPropagator().getLastLeftTupleSink();

    PathMemory pm = (PathMemory) wm.getNodeMemory(rtn);
    SegmentMemory sm = pm.getSegmentMemory();
    assertNotNull( sm.getStagedLeftTuples().getInsertFirst() );
    assertNotNull( sm.getStagedLeftTuples().getInsertFirst().getStagedNext() );
    assertNull( sm.getStagedLeftTuples().getInsertFirst().getStagedNext().getStagedNext() );

    wm.fireAllRules();
    assertNull( sm.getStagedLeftTuples().getInsertFirst() );
    assertEquals(4, list.size() );

    assertEquals("r1", ((Match) list.get(0)).getRule().getName());
    assertEquals( "r1", ((Match)list.get(1)).getRule().getName() );
    assertEquals( "r2", ((Match)list.get(2)).getRule().getName() );
    assertEquals( "r2", ((Match)list.get(3)).getRule().getName() );
}
 
Example #28
Source File: GetFactHandlesCommandTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() { 
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    ksession = kbase.newKieSession();
    runner = ExecutableRunner.create();
    context = ( (RegistryContext) runner.createContext() ).register( KieSession.class, ksession );
}
 
Example #29
Source File: Query2Test.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvalRewrite() throws Exception {
    String str = "" +
    "package org.drools.compiler;\n" +
    "global java.util.List results;\n" +
    "rule \"eval rewrite\"\n" +
    "    when\n" +
    "        $o1 : OrderItem( order.number == 11, $seq : seq == 1 )\n" +
    //"        $o2 : OrderItem( order.number == $o1.order.number, seq != $seq )\n" +
    "        $o2 : Order( items[(Integer) 1] == $o1 ) \n" +
    "    then\n" +
    "        System.out.println( $o1 + \":\" + $o2 );\n" +
    "end        \n";
    
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL );
    
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
    
    final Order order1 = new Order( 11,
                                    "Bob" );
    final OrderItem item11 = new OrderItem( order1,
                                            1 );
    final OrderItem item12 = new OrderItem( order1,
                                            2 );

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession ksession = createKnowledgeSession(kbase);
    ksession.insert( order1 );
    ksession.insert( item11 );
    ksession.insert( item12 );
    
    ksession.fireAllRules();
    

}
 
Example #30
Source File: KnowledgeBaseEvent.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KnowledgeBaseEvent(final InternalKnowledgeBase kBase,
                          final InternalKnowledgePackage pkg,
                          final String function) {
    super( kBase );
    this.kBase = kBase;
    this.pkg = pkg;
    this.rule = null;
    this.function = function;
}