Created
June 26, 2021 12:24
-
-
Save evacchi/38777ced573599e1ec062f50ac25f975 to your computer and use it in GitHub Desktop.
jbang drools.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///usr/bin/env jbang "$0" "$@" ; exit $? | |
//DEPS org.drools:drools-engine:7.56.0.Final | |
//DEPS org.drools:drools-mvel:7.56.0.Final | |
//DEPS org.drools:drools-mvel:7.56.0.Final | |
//DEPS org.slf4j:slf4j-nop:1.7.31 | |
//DEPS com.fasterxml.jackson.core:jackson-databind:2.12.3 | |
// example | |
// jbang <url> '{ "name":"Mario", "age":40 }' '{ "name":"Mark", "age":37 }' | |
package org.kie.example; | |
import static java.lang.System.*; | |
import org.kie.api.*; | |
import org.kie.api.builder.*; | |
import org.kie.api.runtime.*; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
public class drools { | |
public static record Person(String name, int age) {} | |
final static String drl = """ | |
package org.kie.example; | |
import org.kie.example.drools.*; | |
rule MyRule when | |
$mark: Person(name == "Mark") | |
$older: Person(name != "Mark" && age > $mark.age) | |
then | |
System.out.printf("%s is older than %s", $older.name(), $mark.name()); | |
System.out.println(); | |
end | |
"""; | |
public static void main(String... args) throws Exception { | |
var mapper = new ObjectMapper(); | |
var kieSession = makeSession(); | |
for (var s: args) { | |
var person = mapper.readValue(s, Person.class); | |
kieSession.insert(person); | |
} | |
kieSession.fireAllRules(); | |
kieSession.dispose(); | |
} | |
static KieSession makeSession() { | |
var kieServices = KieServices.Factory.get(); | |
var kfs = kieServices.newKieFileSystem(); | |
kfs.write("src/main/resources/rules.drl", | |
kieServices.getResources().newReaderResource(new java.io.StringReader(drl))); | |
var kieBuilder = kieServices.newKieBuilder(kfs).buildAll(); | |
var results = kieBuilder.getResults(); | |
if(results.hasMessages(Message.Level.ERROR)){ | |
err.println("Errors building the rule base."); | |
err.println(results.getMessages()); | |
System.exit(-1); | |
} | |
return kieServices | |
.newKieContainer(kieBuilder.getKieModule().getReleaseId()) | |
.newKieSession(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment