org.kie.api.io.ResourceType Java Examples

The following examples show how to use org.kie.api.io.ResourceType. 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: SegmentMemoryPrototypeTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testSessionCache() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(DRL.getBytes()),
                  ResourceType.DRL );

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

    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kbase.newKieSession();
    try {
        checkKieSession(ksession);
    } finally {
        try {
            ksession.reset();
            checkKieSession(ksession);
        } finally {
            ksession.dispose();
        }
    }
}
 
Example #2
Source File: ExtendsTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeclareExtendsWithFullyQualifiedName() {
    String drl = "package org.drools.extends.test; \n" +
                 "" +
                 "declare org.drools.extends.test.Foo end \n" +
                 "declare org.drools.extends.test.Bar extends org.drools.extends.test.Foo end \n" +
                 "";
    KieServices kieServices = KieServices.Factory.get();
    KieFileSystem kfs = kieServices.newKieFileSystem();
    kfs.write( kieServices.getResources().newByteArrayResource( drl.getBytes() )
                       .setSourcePath( "test.drl" )
                       .setResourceType( ResourceType.DRL ) );
    KieBuilder kieBuilder = kieServices.newKieBuilder( kfs );
    kieBuilder.buildAll();

    assertFalse( kieBuilder.getResults().hasMessages( Message.Level.ERROR ) );

}
 
Example #3
Source File: CompositeKnowledgeBuilderImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private Collection<CompositePackageDescr> buildPackageDescr() {
    Map<String, CompositePackageDescr> packages = new HashMap<>();
    buildResource(packages, ResourceType.DRL, ResourceToPkgDescrMapper.DRL_TO_PKG_DESCR);
    buildResource(packages, ResourceType.GDRL,ResourceToPkgDescrMapper. DRL_TO_PKG_DESCR);
    buildResource(packages, ResourceType.RDRL, ResourceToPkgDescrMapper.DRL_TO_PKG_DESCR);
    buildResource(packages, ResourceType.DESCR, ResourceToPkgDescrMapper.DRL_TO_PKG_DESCR);
    buildResource(packages, ResourceType.DSLR, ResourceToPkgDescrMapper.DSLR_TO_PKG_DESCR);
    buildResource(packages, ResourceType.RDSLR, ResourceToPkgDescrMapper.DSLR_TO_PKG_DESCR);
    buildResource(packages, ResourceType.XDRL, ResourceToPkgDescrMapper.XML_TO_PKG_DESCR);
    buildResource(packages, ResourceType.DTABLE, ResourceToPkgDescrMapper.DTABLE_TO_PKG_DESCR);
    buildResource(packages, ResourceType.TDRL, ResourceToPkgDescrMapper.DRL_TO_PKG_DESCR);
    buildResource(packages, ResourceType.TEMPLATE, ResourceToPkgDescrMapper.TEMPLATE_TO_PKG_DESCR);
    buildResource(packages, ResourceType.GDST, ResourceToPkgDescrMapper.GUIDED_DTABLE_TO_PKG_DESCR);
    this.resourcesByType.remove(ResourceType.DRT); // drt is a template for dtables but doesn't have to be built on its own
    return packages.values();
}
 
Example #4
Source File: ParallelEvaluationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleParallelKieSessionsWithInsertions() throws InterruptedException, ExecutionException, TimeoutException {
    final int NUMBER_OF_PARALLEL_SESSIONS = 5;

    /* Create KIE base */
    StringBuilder sb = new StringBuilder();
    sb.append("global java.util.List list;\n");
    final int ruleNr = 200;

    for (int i = 0; i < ruleNr; i++) {
        sb.append(getRule(i, "insert( $i + 10 );\ninsert( \"\" + ($i + 10) );\n"));
    }
    KieBase kBase = new KieHelper().addContent(sb.toString(), ResourceType.DRL)
            .build(MultithreadEvaluationOption.YES);

    /* Create parallel tasks */
    List<Callable<Void>> tasks = new ArrayList<>();
    for (int i = 0; i < NUMBER_OF_PARALLEL_SESSIONS; i++) {
        tasks.add(getMultipleParallelKieSessionsWithInsertionsCallable(kBase, ruleNr));
    }

    runTasksInParallel(tasks);
}
 
Example #5
Source File: ParallelBuildTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testParallelBuild() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    StringBuilder sb = new StringBuilder();
    int rc = 0;
    for (Class<?> c : classes) {
        sb.append("rule \"rule_" + rc++ + "\"\n");
        sb.append("  when\n");
        sb.append("    a : " + c.getName() + "()\n");
        sb.append("  then\n");
        sb.append("    System.out.print(\".\");\n");
        sb.append("end\n");
        sb.append("\n");
    }

    kbuilder.add(ResourceFactory.newByteArrayResource(sb.toString().getBytes(StandardCharsets.UTF_8)), ResourceType.DRL);
}
 
Example #6
Source File: MatchTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetObjectsAccumulateWithNoMatchingFacts() {
    // DROOLS-1470
    String drl =
            "global java.util.List list\n" +
            "rule R when\n" +
            "  accumulate(\n" +
            "    Object(false);\n" +
            "    $total : count()\n" +
            "  )\n" +
            "then\n" +
            "  list.addAll(((org.drools.core.spi.Activation)kcontext.getMatch()).getObjectsDeep());\n" +
            "end\n";

    KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL).build().newKieSession();

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

    ksession.fireAllRules();
    assertTrue(list.contains(0L));

    ksession.dispose();
}
 
Example #7
Source File: PropertySpecificTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testBetaNodeWithConstraintsNoPropertySpecific() {
    String rule = "package org.drools.compiler.integrationtests\n" +
                  "import " + Person.class.getCanonicalName() + "\n" +
                  "import " + Cheese.class.getCanonicalName() + "\n" +
                  "rule r1\n" +
                  "when\n" +
                  "   Person()\n" +
                  "   Cheese( type == 'brie' )\n" +
                  "then\n" +
                  "end\n";
    
    KieBase kbase = new KieHelper(PropertySpecificOption.ALLOWED).addContent(rule, ResourceType.DRL).build();
    
    ObjectTypeNode otn = getObjectTypeNode(kbase, "Cheese" );
    assertNotNull( otn );

    AlphaNode alphaNode = ( AlphaNode ) otn.getObjectSinkPropagator().getSinks()[0];
    assertEquals( AllSetBitMask.get(), alphaNode.getDeclaredMask() );
    assertEquals( AllSetBitMask.get(), alphaNode.getInferredMask() );
    
    BetaNode betaNode = ( BetaNode ) alphaNode.getObjectSinkPropagator().getSinks()[0];
    
    assertEquals( AllSetBitMask.get(), betaNode.getRightDeclaredMask() );
    assertEquals( AllSetBitMask.get(), betaNode.getRightInferredMask() );
}
 
Example #8
Source File: KieService.java    From Liudao with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 单一规则上线
 *
 * @param packageName
 * @param ruleName
 */
public void addRule(String packageName, String ruleName) {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource(packageName + "/" + ruleName + ".drl"), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        logger.error("Unable to compile drl. " + packageName + ruleName + ".drl");
        return;
    } else {
        if (kbase.getRule(packageName, ruleName) != null) {
            logger.info("update rule: " + packageName + "." + ruleName);
        } else {
            logger.info("add rule: " + packageName + "." + ruleName);
        }
    }

    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    kieSession = kbase.newStatelessKieSession();
    setGlobal();
    printRules();
}
 
Example #9
Source File: ParallelEvaluationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleParallelKieSessionsFireUntilHalt() throws InterruptedException, ExecutionException, TimeoutException {
    final int NUMBER_OF_PARALLEL_SESSIONS = 5;

    /* Create KIE base */
    StringBuilder sb = new StringBuilder(400);
    sb.append("global java.util.List list;\n");
    for (int i = 0; i < 10; i++) {
        sb.append(getRule(i, ""));
    }
    KieBase kbase = new KieHelper().addContent(sb.toString(), ResourceType.DRL)
            .build(MultithreadEvaluationOption.YES);

    List<Callable<Void>> tasks = new ArrayList<>();
    for (int i = 0; i < NUMBER_OF_PARALLEL_SESSIONS; i++) {
        tasks.add(getMultipleParallelKieSessionsFireUntilHaltCallable(kbase, false));
    }

    /* Run tasks in parallel */
    runTasksInParallel(tasks);
}
 
Example #10
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddKPackageCollection() 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() );

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

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

    kpkgs = kbuilder.getKnowledgePackages();
    assertEquals( 2, kpkgs.size() );
}
 
Example #11
Source File: OOPathBindTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void testScenarioBindString(final String drl, final String... expectedResults) {
    final KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
            .build()
            .newKieSession();

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

    final Man bob = new Man( "Bob", 40 );
    final Woman alice = new Woman( "Alice", 38 );

    ksession.insert(bob);
    ksession.insert(alice);
    ksession.fireAllRules();

    assertThat(list).containsExactlyInAnyOrder(expectedResults);
}
 
Example #12
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRedeclareWithInterfaceExtensionAndOverride() {
    final String s1 = "package test;\n" +

                      "declare trait " + Ext.class.getCanonicalName() + " extends " + Base.class.getCanonicalName() + " " +
                      " fld : String " +
                      "end " +

                      "declare trait " + Base.class.getCanonicalName() + " " +
                      "end " +
                      "";

    KieHelper kh = new KieHelper();
    kh.addContent( s1, ResourceType.DRL );

    assertEquals( 0, kh.verify().getMessages( Message.Level.ERROR ).size() );
}
 
Example #13
Source File: SegmentMemoryPrototypeTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testSegmentMemoryPrototype() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(DRL.getBytes()),
                  ResourceType.DRL );

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

    KieSession ksession = kbase.newKieSession();
    try {
        checkKieSession(ksession);
    } finally {
        ksession.dispose();
    }

    // Create a 2nd KieSession (that will use segment memory prototype) and check that it works as the former one
    KieSession ksession2 = kbase.newKieSession();
    try {
        checkKieSession(ksession2);
    } finally {
        ksession2.dispose();
    }
}
 
Example #14
Source File: ParallelEvaluationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testImmediateEventsExpiration() {
    StringBuilder sb = new StringBuilder( 400 );
    sb.append( "global java.util.List list;\n" );
    sb.append( "import " + MyEvent.class.getCanonicalName() + ";\n" );
    sb.append( "declare MyEvent @role( event ) @expires( 1ms ) @timestamp( timestamp ) end\n" );
    for (int i = 0; i < 10; i++) {
        sb.append( getRuleWithEvent( i ) );
    }

    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();

    KieSession ksession = new KieHelper().addContent( sb.toString(), ResourceType.DRL )
                                         .build( EventProcessingOption.STREAM, MultithreadEvaluationOption.YES )
                                         .newKieSession( sessionConfig, null );

    assertTrue( ( (InternalWorkingMemory) ksession ).getAgenda().isParallelAgenda() );

    List<Integer> list = new DebugList<Integer>();
    ksession.setGlobal( "list", list );

    for (int i = 0; i < 10; i++) {
        ksession.insert( new MyEvent( i, i*2L ) );
    }

    ksession.fireAllRules();

    assertEquals(10, list.size());
}
 
Example #15
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testAbductiveLogicNoConstructorFoundError() {
    String droolsSource =
            "package org.drools.abductive.test; \n" +
            "" +
            "import " + Abducible.class.getName() + "; \n" +
            "global java.util.List list; \n" +
            "" +
            "declare Foo \n" +
            "   @Abducible \n" +
            "   id : Integer @key \n" +
            "end \n" +

            "query foo( String $x ) \n" +
                // Foo does not have a String constructor
            "   @Abductive( target=Foo.class ) \n" +
            "end \n" +

            "rule R1 " +
            "when " +
            "   $x : foo( \"x\" ; ) " +
            "then " +
            "   list.add( $x ); " +
            "end \n" +
            "" +
            "";
    /////////////////////////////////////

    KieHelper kieHelper = new KieHelper();
    kieHelper.addContent( droolsSource, ResourceType.DRL );

    Results res = kieHelper.verify();
    assertEquals( 1, res.getMessages( Message.Level.ERROR ).size() );
}
 
Example #16
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testIncrementOperator() {
    String str = "";
    str += "package org.kie \n";
    str += "global java.util.List list \n";
    str += "rule rule1 \n";
    str += "    dialect \"mvel\" \n";
    str += "when \n";
    str += "    $I : Integer() \n";
    str += "then \n";
    str += "    i = $I.intValue(); \n";
    str += "    i += 5; \n";
    str += "    list.add( i ); \n";
    str += "end \n";

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

    final InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());

    final KieSession ksession = createKnowledgeSession(kbase);
    final List list = new ArrayList();
    ksession.setGlobal("list", list);
    ksession.insert(5);

    ksession.fireAllRules();

    assertEquals(1, list.size());
    assertEquals(10, list.get(0));
}
 
Example #17
Source File: ChangeSetTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicAuthentication() throws SAXException,
                           IOException {

    KnowledgeBuilderConfigurationImpl conf = new KnowledgeBuilderConfigurationImpl();
    XmlChangeSetReader xmlReader = new XmlChangeSetReader( conf.getSemanticModules() );
    xmlReader.setClassLoader( ChangeSetTest.class.getClassLoader(), ChangeSetTest.class );

    String str = "";
    str += "<change-set ";
    str += "xmlns='http://drools.org/drools-5.0/change-set' ";
    str += "xmlns:xs='http://www.w3.org/2001/XMLSchema-instance' ";
    str += "xs:schemaLocation='http://drools.org/drools-5.0/change-set https://anonsvn.jboss.org/repos/labs/labs/jbossrules/trunk/drools-api/src/main/resources/change-set-1.0.0.xsd' >";
    str += "    <add> ";
    str += "        <resource source='http://localhost:8081/jboss-brms/org.kie.guvnor.Guvnor/package/defaultPackage/LATEST' type='PKG' basicAuthentication='enabled' username='admin' password='pwd'/>";
    str += "    </add> ";
    str += "</change-set>";

    StringReader reader = new StringReader( str );
    ChangeSet changeSet = xmlReader.read( reader );

    assertEquals( 1,
                  changeSet.getResourcesAdded().size() );
    UrlResource resource = ( UrlResource ) ((List)changeSet.getResourcesAdded()).get( 0 );
    assertEquals( "http://localhost:8081/jboss-brms/org.kie.guvnor.Guvnor/package/defaultPackage/LATEST",
                  resource.getURL().toString() );
    assertEquals( "enabled", resource.getBasicAuthentication() );
    assertEquals( "admin", resource.getUsername() );
    assertEquals( "pwd", resource.getPassword() );
    assertEquals( ResourceType.PKG,
                  resource.getResourceType() );
}
 
Example #18
Source File: MultithreadTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testJittingShortComparison() {
    // DROOLS-1633
    final String drl =
            "import " + BeanA.class.getCanonicalName() + "\n;" +
                    "global java.util.List list;" +
                    "rule R when\n" +
                    "  $a1: BeanA($sv1 : shortValue)\n" +
                    "  $b2: BeanA(shortValue != $sv1)\n" +
                    "then\n" +
                    "  list.add(\"FIRED\");\n" +
                    "end";

    final List<String> list = Collections.synchronizedList(new ArrayList());
    final RuleBaseConfiguration rbc = (RuleBaseConfiguration) KieServices.Factory.get().newKieBaseConfiguration();
    rbc.setJittingThreshold(0);
    final KieBase kbase = new KieHelper().addContent(drl, ResourceType.DRL).build(rbc);

    final int threadNr = 1000;
    final Thread[] threads = new Thread[threadNr];
    for (int i = 0; i < threadNr; i++) {
        threads[i] = new Thread(new SessionRunner(kbase, list));
    }

    for (int i = 0; i < threadNr; i++) {
        threads[i].start();
    }

    assertTimeoutPreemptively(Duration.ofSeconds(10), () -> {
        for (int i = 0; i < threadNr; i++) {
            try {
                threads[i].join();
            } catch (final InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    });

    assertThat(list).hasSize(0);
}
 
Example #19
Source File: IntegrationInterfacesTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieBase getKnowledgeBase(final Reader[] readers) throws IOException,
                                                              ClassNotFoundException {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    for ( Reader reader : readers ) {
        kbuilder.add( ResourceFactory.newReaderResource(reader),
                      ResourceType.DRL );
    }
    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());
    KieBase kbase = getKnowledgeBase( kbuilder );
    return kbase;
}
 
Example #20
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeDeclarationWithInnerClasses() {
    // DROOLS-150
    String str = "";
    str += "package org.drools.compiler;\n" +
           "\n" +
           "import org.drools.compiler.compiler.TypeDeclarationTest.EventBar.*;\n" +
           "" +
           "declare Foo\n" +
           " @role( event )\n" +
           "end\n" +
           "" +
           "rule R when Foo() then end";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
                  ResourceType.DRL );
    System.err.println( kbuilder.getErrors() );
    assertFalse( kbuilder.hasErrors() );

    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
    kBase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession knowledgeSession = kBase.newKieSession();
    FactHandle handle = knowledgeSession.insert( new EventBar.Foo() );

    assertTrue( handle instanceof EventFactHandle );

}
 
Example #21
Source File: AbstractKieModule.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public ResourceConfiguration getResourceConfiguration(String fileName) {
    ResourceConfiguration conf = resourceConfigurationCache.get(fileName);
    if (conf != null) {
        return conf;
    }
    Properties prop = new Properties();
    if (isAvailable(fileName + ".properties")) {
        // configuration file available
        try {
            prop.load(new ByteArrayInputStream(getBytes(fileName + ".properties")));
        } catch (IOException e) {
            log.error(String.format("Error loading resource configuration from file: %s.properties", fileName));
        }
    }
    if (ResourceType.DTABLE.matchesExtension(fileName)) {
        int lastDot = fileName.lastIndexOf( '.' );
        if (lastDot >= 0 && fileName.length() > lastDot+1) {
            String extension = fileName.substring( lastDot+1 );
            Object confClass = prop.get(ResourceTypeImpl.KIE_RESOURCE_CONF_CLASS);
            if (confClass == null || confClass.toString().equals( ResourceConfigurationImpl.class.getCanonicalName() )) {
                prop.setProperty( ResourceTypeImpl.KIE_RESOURCE_CONF_CLASS, DecisionTableConfigurationImpl.class.getName() );
            }
            prop.setProperty(DecisionTableConfigurationImpl.DROOLS_DT_TYPE, DecisionTableInputType.valueOf( extension.toUpperCase() ).toString());
        }
    }
    conf = prop.isEmpty() ? null : ResourceTypeImpl.fromProperties(prop);
    resourceConfigurationCache.put(fileName, conf);
    return conf;
}
 
Example #22
Source File: PassiveQueryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPassiveQueryDataDriven() throws Exception {
    String str =
            "global java.util.List list\n" +
            "query Q (Integer i)\n" +
            "    String( this == i.toString() )\n" +
            "end\n" +
            "rule R @Propagation(IMMEDIATE) when\n" +
            "    $i : Integer()\n" +
            "    ?Q( $i; )\n" +
            "then\n" +
            "    list.add( $i );\n" +
            "end\n";

    KieSession ksession = new KieHelper()
            .addContent(str, ResourceType.DRL)
            .build()
            .newKieSession();

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

    ksession.insert(1);
    ksession.insert("1");
    ksession.fireAllRules();
    assertEquals(0, list.size());
}
 
Example #23
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 #24
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPackageImports() {
    String str = "";
    str += "package org.kie \n";
    str += "dialect \"mvel\"\n";
    str += "import org.acme.healthcare.* \n";
    str += "import org.acme.insurance.* \n";
    str += "import org.acme.sensors.SensorReading \n";
    str += "rule rule1 \n";
    str += "  when \n";
    str += "    eval(true)\n";
    str += "  then \n";
    str += "    insert(new Claim());         // from org.acme.healthcare.* \n";
    str += "    insert(new Policy());        // from org.acme.insurance.* \n";
    str += "    insert(new SensorReading()); // from org.acme.sensor.SensorReading \n";
    str += "end\n";

    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        throw new RuntimeException(kbuilder.getErrors().toString());
    }
    final InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());

    final KieSession ksession = createKnowledgeSession(kbase);
    final int result = ksession.fireAllRules();
    assertEquals(1, result);
    final Collection<? extends Object> insertedObjects = ksession.getObjects();
    assertEquals(3, insertedObjects.size());
}
 
Example #25
Source File: KieSessionUtils.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
public static KieSession createKieSessionFromDRL(String drl) throws Exception{
    KieHelper kieHelper = new KieHelper();
    kieHelper.addContent(drl, ResourceType.DRL);
    Results results = kieHelper.verify();
    if (results.hasMessages(Message.Level.WARNING, Message.Level.ERROR)) {
        List<Message> messages = results.getMessages(Message.Level.WARNING, Message.Level.ERROR);
        for (Message message : messages) {
            System.out.println("Error: "+message.getText());
        }
        // throw new IllegalStateException("Compilation errors were found. Check the logs.");
    }
    return kieHelper.build().newKieSession();
}
 
Example #26
Source File: OOPathOnGraphTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testOOPathOnGraphWithReactiveContentModification() {
    String drl =
            "import org.drools.compiler.oopath.graph.*;\n" +
            "import " + Library.class.getCanonicalName() + ";\n" +
            "import " + Book.class.getCanonicalName() + ";\n" +
            "import " + Person.class.getCanonicalName() + ";\n" +
            "global java.util.List list\n" +
            "\n" +
            "rule R when\n" +
            "  Vertex( it instanceof Library, $a : /outVs/outVs/it#Person[ age > 25 ] )\n" +
            "then\n" +
            "  list.add( $a.getName() );\n" +
            "end\n";

    KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
                                         .build()
                                         .newKieSession();

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

    Vertex<Library> library = getGraph();
    ksession.insert( library );
    ksession.fireAllRules();

    assertEquals( 1, list.size() );
    assertTrue( list.contains( "Mario" ) );
    list.clear();

    Person raoul = (Person)library.getOutVs().get(0).getOutVs().get(0).getIt();
    assertEquals( "Raoul", raoul.getName() );
    raoul.setAge( raoul.getAge() + 1 );

    ksession.fireAllRules();
    assertEquals( 1, list.size() );
    assertTrue( list.contains( "Raoul" ) );
}
 
Example #27
Source File: SessionsPoolTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatelessSequential() {
    // DROOLS-3228
    String drl =
            "import " + AtomicInteger.class.getCanonicalName() + ";\n" +
            "global java.util.List list\n" +
            "rule R1 when\n" +
            "  String()\n" +
            "  Integer()\n" +
            "then\n" +
            "  list.add(\"OK\");\n" +
            "end";

    KieBase kbase = new KieHelper().addContent( drl, ResourceType.DRL ).build( SequentialOption.YES );
    KieSessionsPool pool = kbase.newKieSessionsPool( 1 );

    StatelessKieSession ksession = pool.newStatelessKieSession();

    List<String> list = new ArrayList<>();

    List<Command> commands = new ArrayList<>(5);
    commands.add(CommandFactory.newSetGlobal("list", list));
    commands.add(CommandFactory.newInsert("test"));
    commands.add(CommandFactory.newInsert(1));
    commands.add(CommandFactory.newFireAllRules());
    ksession.execute(CommandFactory.newBatchExecution(commands));

    assertEquals(1, list.size());

    list.clear();

    ksession.execute(CommandFactory.newBatchExecution(commands));

    assertEquals(1, list.size());

    pool.shutdown();
}
 
Example #28
Source File: DateCoercionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDateCoercionWithNestedOr() {
    // BZ-1253575
    String drl = "import java.util.Date\n" +
                 "global java.util.List list\n" +
                 "declare DateContainer\n" +
                 "     date: Date\n" +
                 "end\n" +
                 "\n" +
                 "rule Init when\n" +
                 "then\n" +
                 "    insert(new DateContainer(new Date( 1439882189744L )));" +
                 "end\n" +
                 "\n" +
                 "rule \"Test rule\"\n" +
                 "when\n" +
                 "    $container: DateContainer( (date >= \"19-Jan-2014\" && date <= \"03-Dec-2015\" ) || (date >= \"17-Dec-2016\" && date <= \"02-Jan-2017\" ) )\n" +
                 "then\n" +
                 "    list.add(\"working\");\n" +
                 "end\n";

    KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
                                         .build()
                                         .newKieSession();

    List<String> list = new ArrayList<String>();
    ksession.setGlobal( "list", list );
    ksession.fireAllRules();
    assertEquals( 1, list.size() );
    assertEquals( "working", list.get( 0 ) );
}
 
Example #29
Source File: StrictAnnotationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testJavaSqlTimestamp() {
    String str =
            "package " + Message.class.getPackage().getName() + "\n" +
            "@Role( Role.Type.EVENT ) @Timestamp( \"startTime\" ) @Duration( \"duration\" )\n" +
            "declare " + Message.class.getCanonicalName() + "\n" +
            "end\n";

    KieSession ksession = new KieHelper()
            .setKieModuleModel(KieServices.Factory.get().newKieModuleModel()
                                                  .setConfigurationProperty(LanguageLevelOption.PROPERTY_NAME,
                                                                            LanguageLevelOption.DRL6_STRICT.toString()))
            .addContent(str, ResourceType.DRL)
            .build()
            .newKieSession();
    try {
        Message msg = new Message();
        msg.setStartTime( new Timestamp( 10000 ) );
        msg.setDuration( 1000l );

        EventFactHandle efh = (EventFactHandle) ksession.insert( msg );
        assertEquals( 10000,
                      efh.getStartTimestamp() );
        assertEquals( 1000,
                      efh.getDuration() );
    } finally {
        ksession.dispose();
    }
}
 
Example #30
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() );
}