org.kie.api.definition.KiePackage Java Examples

The following examples show how to use org.kie.api.definition.KiePackage. 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: RuleEngine.java    From support-rulesengine with Apache License 2.0 6 votes vote down vote up
public List<String> getRulenames() {
  List<String> result = new ArrayList<>();
  try {
    KiePackage kpkg = kbase.getKiePackage(packageName);
    if (kpkg != null) {
      Collection<Rule> rules = kpkg.getRules();
      if (rules != null) {
        for (Rule rule : rules) {
          result.add(rule.getName());
        }
      }
    }
    return result;
  } catch (Exception ex) {
    logger.error(ex.getMessage());
    throw new ServiceException(ex);
  }
}
 
Example #2
Source File: AbstractKieModule.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public InternalKnowledgeBase createKieBase( KieBaseModelImpl kBaseModel, KieProject kieProject, ResultsImpl messages, KieBaseConfiguration conf ) {
    KnowledgePackagesBuildResult knowledgePackagesBuildResult = buildKnowledgePackages(kBaseModel, kieProject, messages);
    if(knowledgePackagesBuildResult.hasErrors()) {
        return null;
    }

    Collection<KiePackage> pkgs = knowledgePackagesBuildResult.getPkgs();
    checkStreamMode( kBaseModel, conf, pkgs );

    ClassLoader cl = kieProject.getClassLoader();
    if (conf == null) {
        conf = getKnowledgeBaseConfiguration(kBaseModel, cl);
    } else if (conf instanceof RuleBaseConfiguration ) {
        ((RuleBaseConfiguration)conf).setClassLoader(cl);
    }

    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase(kBaseModel.getName(), conf );
    kBase.addPackages( pkgs );
    return kBase;
}
 
Example #3
Source File: DescrBuilderTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuleRHSOptional() throws InstantiationException,
                                   IllegalAccessException {
    PackageDescr pkg = DescrFactory.newPackage()
            .name( "org.drools.compiler" )
            .newRule().name( "r1" )
                .lhs()
                    .pattern("StockTick").constraint( "company == \"RHT\"" ).end()
                .end()
            .end()
            .getDescr();

    KiePackage kpkg = compilePkgDescr( pkg );
    assertEquals( "org.drools.compiler",
                  kpkg.getName() );
    
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( Collections.singletonList( kpkg ) );
    
    KieSession ksession = kbase.newKieSession();
    ksession.insert( new StockTick(1, "RHT", 80, 1 ) );
    int rules = ksession.fireAllRules();
    assertEquals( 1, rules );
}
 
Example #4
Source File: BaseTest.java    From iot-ocp with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    KieServices kieServices = KieServices.Factory.get();

    KieContainer kContainer = kieServices.getKieClasspathContainer();
    Results verifyResults = kContainer.verify();
    for (Message m : verifyResults.getMessages()) {
        LOG.debug("Kie container message: {}", m);
    }

    KieBase kieBase = kContainer.getKieBase();
    LOG.debug("Created kieBase");

    for ( KiePackage kp : kieBase.getKiePackages() ) {
        for (Rule rule : kp.getRules()) {
            LOG.debug("kp " + kp + " rule " + rule.getName());
        }
    }

    session = kieBase.newKieSession();
    LOG.info(session.getGlobals().toString());
    Logger kieLogger = LoggerFactory.getLogger(this.getClass());
   // session.setGlobal("logger",kieLogger);
}
 
Example #5
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testSignedSerialization2() throws Exception {
    try {
        // set only the serialisation properties, but not the deserialization
        setPrivateKeyProperties();

        try {
            // Test package serialization/deserialization
            Collection<KiePackage>  kpkgs = loadKnowledgePackages("../test_Dynamic1_0.drl");
            fail( "Deserialisation should have failed." );
        } catch ( Exception e ) {
            // success
        }
    } finally {
        unsetPrivateKeyProperties();
    }
}
 
Example #6
Source File: RemoveRuleTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private Collection<KiePackage> buildKnowledgePackage(String ruleName, String rule) {
    String str = "";
    str += "package org.kie \n";
    str += "import " + A.class.getCanonicalName() + "\n" ;
    str += "import " + B.class.getCanonicalName() + "\n" ;
    str += "import " + C.class.getCanonicalName() + "\n" ;
    str += "import " + D.class.getCanonicalName() + "\n" ;
    str += "import " + E.class.getCanonicalName() + "\n" ;
    str += "global java.util.List list \n";

    int i = 0;
    str += "rule " + ruleName + "  when \n";
    str +=  rule;
    str += "then \n";
    str += " list.add( kcontext.getMatch() );\n";
    str += "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add( ResourceFactory.newByteArrayResource(str.getBytes()),
                  ResourceType.DRL );

    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());

    return kbuilder.getKnowledgePackages();
}
 
Example #7
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 #8
Source File: SerializationSecurityPolicyTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerialization() throws IOException, ClassNotFoundException {
    final String rule =
            " rule R " +
            " when " +
            " then " +
            "     System.out.println(\"consequence!\"); " +
            " end";

    final KieServices kieServices = KieServices.get();
    final Resource drlResource = kieServices.getResources().newByteArrayResource(
            rule.getBytes(StandardCharsets.UTF_8.name()), StandardCharsets.UTF_8.name());
    drlResource.setResourceType(ResourceType.DRL);
    drlResource.setTargetPath("test.drl");
    final KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
    kieFileSystem.write(drlResource);
    final KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
    kieBuilder.buildAll();

    final KieBase kieBase = kieServices.newKieContainer(kieBuilder.getKieModule().getReleaseId()).getKieBase();

    final Collection<KiePackage> kpkgs = kieBase.getKiePackages();
    final Collection<KiePackage> newCollection = new ArrayList<>();
    for (KiePackage kpkg : kpkgs) {
        kpkg = SerializationHelper.serializeObject(kpkg);
        newCollection.add(kpkg);
    }
    ((InternalKnowledgeBase) kieBase).addPackages(newCollection);

    final KieSession kieSession = kieBase.newKieSession();
    assertThat(kieSession.fireAllRules()).isEqualTo(1);
}
 
Example #9
Source File: MergePackageTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testMergePackageWithSameRuleNames() throws Exception {
    final InternalKnowledgeBase kbase =
            (InternalKnowledgeBase) SerializationHelper.serializeObject(loadKnowledgeBase("test_MergePackageWithSameRuleNames1.drl"));
    final Collection<KiePackage> kpkgs =
            loadKnowledgePackages("test_MergePackageWithSameRuleNames2.drl");
    kbase.addPackages(kpkgs);

    final KieSession ksession = createKnowledgeSession(kbase);

    final List results = new ArrayList();
    ksession.setGlobal("results", results);
    ksession.fireAllRules();
    assertEquals(1, results.size());
    assertEquals("rule1 for the package2", results.get(0));
}
 
Example #10
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testRepeatedDeclarationInMultiplePackages() {
    String str =
            "package org.drools.test1;\n" +
            "import org.drools.compiler.Cheese;\n" +
            "" +
            "rule R\n" +
            "when Cheese() then end \n" +
            "";
    String str2 =
            "package org.drools.test2;\n" +
            "import org.drools.compiler.Cheese;\n" +
            "" +
            "rule S\n" +
            "when Cheese() then end \n" +
            "";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ), ResourceType.DRL );
    kbuilder.add( ResourceFactory.newByteArrayResource( str2.getBytes() ), ResourceType.DRL );

    assertEquals( 3, kbuilder.getKnowledgePackages().size() );
    for ( KiePackage kp : kbuilder.getKnowledgePackages() ) {
        KnowledgePackageImpl kpi = (KnowledgePackageImpl) kp;
        TypeDeclaration cheez = kpi.getTypeDeclaration( "Cheese" );
        if ( "org.drools.compiler".equals( kpi.getName() ) ) {
            assertNotNull( cheez );
        } else {
            assertNull( cheez );
        }

    }
}
 
Example #11
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * In this case we are dealing with facts which are not on the systems classpath.
 */
@Test
public void testSerializabilityWithJarFacts() throws Exception {
    MapBackedClassLoader loader = new MapBackedClassLoader( this.getClass().getClassLoader() );

    JarInputStream jis = new JarInputStream( this.getClass().getResourceAsStream( "/billasurf.jar" ) );

    JarEntry entry = null;
    byte[] buf = new byte[1024];
    int len = 0;
    while ( (entry = jis.getNextJarEntry()) != null ) {
        if ( !entry.isDirectory() ) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ( (len = jis.read( buf )) >= 0 ) {
                out.write( buf,
                           0,
                           len );
            }
            loader.addResource( entry.getName(),
                                out.toByteArray() );
        }
    }

    String drl = "package foo.bar \n" +
                 "import com.billasurf.Board\n" +
                 "rule 'MyGoodRule' \n dialect 'mvel' \n when " +
                 "   Board() " +
                 "then \n" +
                 " System.err.println(42); \n" +
                 "end\n";


    KnowledgeBuilderConfiguration kbuilderConf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(null, loader);

    Collection<KiePackage>  kpkgs = loadKnowledgePackagesFromString(kbuilderConf, drl);

    kpkgs = SerializationHelper.serializeObject( kpkgs, loader );

}
 
Example #12
Source File: DslTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void checkDSLExpanderTest(KnowledgeBuilder kbuilder) throws IOException, ClassNotFoundException {
    assertFalse( kbuilder.hasErrors() );
    final String err = kbuilder.getErrors().toString();
    assertEquals( "",
                  err );
    assertEquals( 0,
                  kbuilder.getErrors().size() );

    // the compiled package
    final Collection<KiePackage> pkgs = kbuilder.getKnowledgePackages();
    assertEquals( 2, pkgs.size() );

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( pkgs );
    kbase    = SerializationHelper.serializeObject(kbase);

    KieSession session = createKnowledgeSession(kbase);
    session.insert( new Person( "Bob",
                           "http://foo.bar" ) );
    session.insert( new Cheese( "stilton",
                           42 ) );

    final List messages = new ArrayList();
    session.setGlobal( "messages",
                  messages );
    session.fireAllRules();

    assertEquals( 1, messages.size() );
}
 
Example #13
Source File: DescrBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamedConsequence() {
    PackageDescr pkg = DescrFactory.newPackage()
            .name( "org.drools.compiler" )
            .newRule().name( "test" )
                .lhs()
                    .pattern("Cheese").constraint( "type == \"stilton\"" ).end()
                    .namedConsequence().name("c1").end()
                    .pattern("Cheese").constraint( "type == \"cheddar\"" ).end()
                .end()
                .rhs( "// do something" )
                .namedRhs( "c1", "// do something else" )
            .end()
            .getDescr();

    assertEquals( 1,
                  pkg.getRules().size() );

    KiePackage kpkg = compilePkgDescr( pkg );
    assertEquals( "org.drools.compiler",
            kpkg.getName() );

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( Collections.singletonList( kpkg ) );
    KieSession ksession = createKnowledgeSession(kbase);

    Cheese stilton = new Cheese( "stilton", 5 );
    Cheese cheddar = new Cheese( "cheddar", 7 );
    Cheese brie = new Cheese( "brie", 5 );

    ksession.insert( stilton );
    ksession.insert( cheddar );
    ksession.insert( brie );

    int rules = ksession.fireAllRules();
    assertEquals( 2,
                  rules );
}
 
Example #14
Source File: DescrBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPackageAttributes() {
    PackageDescr pkg = DescrFactory.newPackage()
            .name( "org.drools" )
            // first syntax
            .attribute( "dialect" ).value( "mvel" ).end()
            // second syntax
            .attribute( "salience",
                        "10" )
            // third syntax
            .attribute( "lock-on-active",
                        "true",
                        AttributeDescr.Type.BOOLEAN )
            .getDescr();

    assertEquals( "org.drools",
                  pkg.getName() );
    assertEquals( 3,
                  pkg.getAttributes().size() );
    assertEquals( "mvel",
                  pkg.getAttribute( "dialect" ).getValue() );
    assertEquals( "10",
                  pkg.getAttribute( "salience" ).getValue() );
    assertEquals( "true",
                  pkg.getAttribute( "lock-on-active" ).getValue() );
    assertEquals( AttributeDescr.Type.BOOLEAN,
                  pkg.getAttribute( "lock-on-active" ).getType() );
    assertNull( pkg.getAttribute( "no-loop" ) );

    KiePackage kpkg = compilePkgDescr( pkg );
    assertEquals( "org.drools",
                  kpkg.getName() );
}
 
Example #15
Source File: KnowledgeBaseImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * Add a <code>Package</code> to the network. Iterates through the
 * <code>Package</code> adding Each individual <code>Rule</code> to the
 * network. Before update network each referenced <code>WorkingMemory</code>
 * is locked.
 *
 * @param newPkgs The package to add.
 */
@Override
public void addPackages( Collection<? extends KiePackage> newPkgs ) {
    final List<InternalKnowledgePackage> clonedPkgs = new ArrayList<>();
    for (KiePackage newPkg : newPkgs) {
        clonedPkgs.add(((InternalKnowledgePackage)newPkg).deepCloneIfAlreadyInUse(rootClassLoader));
    }

    clonedPkgs.sort(Comparator.comparing( (InternalKnowledgePackage p) -> p.getRules().size() ).reversed().thenComparing( InternalKnowledgePackage::getName ));
    enqueueModification( () -> internalAddPackages( clonedPkgs ) );
}
 
Example #16
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KiePackage getKnowledgePackage(Collection<KiePackage> pkgs, String name) {
	for ( KiePackage pkg : pkgs ) {
		if ( pkg.getName().equals( name ) ) {
			return pkg;
		}
	}
	return null;
}
 
Example #17
Source File: AbstractBaseTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieSession createKieSession(boolean serializeKbase, KiePackage... pkg) throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(Arrays.asList(pkg));
    if( serializeKbase ) { 
        kbase = JbpmSerializationHelper.serializeObject( kbase );
    }

    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption( ForceEagerActivationOption.YES );
    return kbase.newKieSession(conf, null);
}
 
Example #18
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected KieBase loadKnowledgeBase(KnowledgeBuilderConfiguration kbuilderConf,KieBaseConfiguration kbaseConf, PackageDescr descr) {
    Collection<KiePackage> knowledgePackages = loadKnowledgePackages(kbuilderConf, descr);

    if (kbaseConf == null) {
        kbaseConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kbaseConf);
    kbase.addPackages(knowledgePackages);
    try {
        kbase = SerializationHelper.serializeObject(kbase);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return kbase;
}
 
Example #19
Source File: KnowledgeBuilderImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<KiePackage> getKnowledgePackages() {
    if (hasErrors()) {
        return new ArrayList<>(0);
    }

    InternalKnowledgePackage[] pkgs = getPackages();
    List<KiePackage> list = new ArrayList<>(pkgs.length);

    Collections.addAll(list, pkgs);

    return list;
}
 
Example #20
Source File: MVELReturnValueEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public Object evaluate(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 = (InternalWorkingMemory) context.getKieRuntime();
    
    VariableResolverFactory factory 
        = unit.getFactory( context, 
                           null, // No previous declarations
                           null, // No rule
                           null, // No "right object" 
                           null, // No (left) tuples
                           vars, 
                           internalWorkingMemory,
                           (GlobalResolver) context.getKieRuntime().getGlobals() );

    // do we have any functions for this namespace?
    KiePackage pkg = context.getKieRuntime().getKieBase().getKiePackage("MAIN");
    if ( pkg instanceof KnowledgePackageImpl) {
        MVELDialectRuntimeData data = ( MVELDialectRuntimeData ) ((KnowledgePackageImpl) pkg).getDialectRuntimeRegistry().getDialectData( id );
        factory.setNextFactory( data.getFunctionFactory() );
    }

    Object value = MVELSafeHelper.getEvaluator().executeExpression( this.expr,
                                        null,
                                        factory );

    if ( !(value instanceof Boolean) ) {
        throw new RuntimeException( "Constraints must return boolean values: " + 
    		unit.getExpression() + " returns " + value + 
    		(value == null? "" : " (type=" + value.getClass()));
    }
    return ((Boolean) value).booleanValue();

}
 
Example #21
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public Collection<KiePackage> loadKnowledgePackages(KnowledgeBuilderConfiguration kbuilderConf, PackageDescr descr) {
    if (kbuilderConf == null) {
        kbuilderConf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration();
    }
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(kbuilderConf);
    kbuilder.add(ResourceFactory.newDescrResource(descr), ResourceType.DESCR);
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    Collection<KiePackage> knowledgePackages = kbuilder.getKnowledgePackages();
    return knowledgePackages;
}
 
Example #22
Source File: AddRuleTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private Collection<KiePackage> buildKnowledgePackage(String ruleName, String rule) {
    String str = "";
    str += "package org.kie \n";
    str += "import " + A.class.getCanonicalName() + "\n" ;
    str += "import " + B.class.getCanonicalName() + "\n" ;
    str += "import " + C.class.getCanonicalName() + "\n" ;
    str += "import " + D.class.getCanonicalName() + "\n" ;
    str += "import " + E.class.getCanonicalName() + "\n" ;
    str += "global java.util.List list \n";

    int i = 0;
    str += "rule " + ruleName + "  when \n";
    str +=  rule;
    str += "then \n";
    str += " list.add( kcontext.getMatch() );\n";
    str += "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add( ResourceFactory.newByteArrayResource(str.getBytes()),
                  ResourceType.DRL );

    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());

    return kbuilder.getKnowledgePackages();
}
 
Example #23
Source File: SerializedPackageMergeTwoSteps1Test.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildAndSerializePackagesInTwoSteps1() {
	String str1 =
			"package com.sample.packageA\n" +
					"import org.drools.compiler.Person\n" +
					"global java.util.List list\n" +
					"rule R1 when\n" +
					"  $p : Person( name == \"John\" )\n" +
					"then\n" +
					"  list.add($p);" +
					"end\n";

	String str2 =
			"package com.sample.packageB\n" +
					"import org.drools.compiler.Person\n" +
					"global java.util.List list\n" +
					"rule R2 when\n" +
					"  $p : Person()\n" +
					"then\n" +
					"  list.add($p);" +
					"end\n";

	// Create 2 knowledgePackages separately
	KnowledgeBuilder builder1 = KnowledgeBuilderFactory.newKnowledgeBuilder();
	builder1.add( ResourceFactory.newByteArrayResource( str1.getBytes() ), ResourceType.DRL );
	Collection<KiePackage> knowledgePackages1 = builder1.getKnowledgePackages();

	// serialize the first package to a file
	writeKnowledgePackage(knowledgePackages1, BINPKG[0]);

	KnowledgeBuilder builder2 = KnowledgeBuilderFactory.newKnowledgeBuilder();
	builder2.add( ResourceFactory.newByteArrayResource( str2.getBytes() ), ResourceType.DRL );
	Collection<KiePackage> knowledgePackages2 = builder2.getKnowledgePackages();

	// serialize the second package to a file
	writeKnowledgePackage(knowledgePackages2, BINPKG[1]);               
}
 
Example #24
Source File: DynamicRulesTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDynamicRuleAdditionsWithEntryPoints() throws Exception {
    Collection<KiePackage> kpkgs = loadKnowledgePackages("test_DynamicWithEntryPoint.drl" );
    InternalKnowledgeBase kbase = (InternalKnowledgeBase) getKnowledgeBase();

    KieSession ksession = createKnowledgeSession( kbase );

    // now lets add some knowledge to the kbase
    kbase.addPackages( kpkgs );

    List<StockTick> results = new ArrayList<StockTick>();
    ksession.setGlobal( "results",
                        results );

    EntryPoint ep = ksession.getEntryPoint( "in-channel" );
    ep.insert( new StockTick( 1,
                              "RHT",
                              20,
                              10000 ) );
    ep.insert( new StockTick( 2,
                              "RHT",
                              21,
                              15000 ) );
    ep.insert( new StockTick( 3,
                              "RHT",
                              22,
                              20000 ) );

    ksession.fireAllRules();
    assertEquals( 3,
                  results.size() );

}
 
Example #25
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddPackageArray() throws Exception {
    String rule = "package org.drools.compiler.test\n" +
                  "import org.drools.compiler.StockTick\n" +
                  "declare StockTick @role(event) end\n" +
                  "rule R1 when\n" +
                  "   StockTick()\n" +
                  "then\n" +
                  "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(rule.getBytes()), ResourceType.DRL);

    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());

    Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();
    assertEquals( 2, kpkgs.size() );
}
 
Example #26
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddPackageSingle() throws Exception {
    String rule = "package org.drools.compiler.test\n" +
                  "import org.drools.compiler.StockTick\n" +
                  "rule R1 when\n" +
                  "   StockTick()\n" +
                  "then\n" +
                  "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(rule.getBytes()), ResourceType.DRL);

    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());

    Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();
    assertEquals( 2, kpkgs.size() );
    KiePackage kpkg = kpkgs.iterator().next();
    assertEquals( 1, kpkg.getRules().size() );
}
 
Example #27
Source File: DescrBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testFunctions() {
    PackageDescr pkg = DescrFactory.newPackage()
            .name( "org.drools" )
            // functions
            .newFunctionImport().target( "java.lang.Math.max" ).end()
            .newFunction().returnType( "long" ).name( "myMax" )
                .parameter( "long",
                            "v1" ).parameter( "long",
                                              "v2" )
                .body( "return max(v1, v2);" )
            .end()
            // rule
            .newRule().name( "test" )
                .lhs()
                    .eval().constraint( "myMax(5, 10) == 10" ).end()
                .end()
                .rhs( "// do something" )
            .end()
            .getDescr();

    assertEquals( 1,
                  pkg.getFunctionImports().size() );
    assertEquals( 1,
                  pkg.getFunctions().size() );
    assertEquals( 1,
                  pkg.getRules().size() );

    KiePackage kpkg = compilePkgDescr( pkg );
    assertEquals( "org.drools",
                  kpkg.getName() );

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( Collections.singletonList( kpkg ) );
    KieSession ksession = createKnowledgeSession(kbase);
    int rules = ksession.fireAllRules();
    assertEquals( 1,
                  rules );
}
 
Example #28
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 #29
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddKPackageSingle() throws Exception {
    String rule = "package org.drools.compiler.test\n" +
                  "import org.drools.compiler.StockTick\n" +
                  "rule R1 when\n" +
                  "   StockTick()\n" +
                  "then\n" +
                  "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( rule.getBytes() ), ResourceType.DRL );
    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());

    Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();
    assertEquals( 2, kpkgs.size() );

    KiePackage kpkg = kpkgs.iterator().next();

    byte[] skpkg = DroolsStreamUtils.streamOut( kpkg );

    kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( skpkg ), ResourceType.PKG );
    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());

    kpkgs = kbuilder.getKnowledgePackages();
    assertEquals( 1, kpkgs.size() );
    kpkg = kpkgs.iterator().next();
    assertEquals( 1, kpkg.getRules().size() );
}
 
Example #30
Source File: StatelessSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private StatelessKieSession getSession2(final Resource resource) throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( resource, ResourceType.DRL );
    
    if (kbuilder.hasErrors() ) {
        System.out.println( kbuilder.getErrors() );
    }
    
    assertFalse( kbuilder.hasErrors() );
    final Collection<KiePackage> pkgs = kbuilder.getKnowledgePackages();

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    
   
    kbase.addPackages( pkgs );
    kbase    = SerializationHelper.serializeObject( kbase );
    final StatelessKieSession session = kbase.newStatelessKieSession();

    session.setGlobal( "list",
                       this.list );
    session.setGlobal( "cheesery",
                       this.cheesery );
    return session;
}