### Example FindApprovedLoansEndpoint REST Endpoint Setup Source: https://docs.drools.org/latest/drools-docs/drools/migration-guide/index.html Setup for a REST endpoint that exposes rule evaluation. It uses a static KieContainer for efficient rule loading. ```java @Path("/find-approved") public class FindApprovedLoansEndpoint { private static final KieContainer kContainer = KieServices.Factory.get().newKieClasspathContainer(); @POST() @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public List executeQuery(LoanAppDto loanAppDto) { KieSession session = kContainer.newKieSession(); List approvedApplications = new ArrayList<>(); session.setGlobal("approvedApplications", approvedApplications); session.setGlobal("maxAmount", loanAppDto.getMaxAmount()); loanAppDto.getLoanApplications().forEach(session::insert); session.fireAllRules(); session.dispose(); return approvedApplications; } } ``` -------------------------------- ### Build and Install Maven Project Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Standard Maven command to build and install the project. This is a prerequisite for deploying Drools resources to the classpath. ```bash mvn install ``` -------------------------------- ### BatchExecution Command Example Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Executes a batch of commands, including inserting objects, starting a process, and executing a query. Results from commands with out identifiers are added to the ExecutionResults. ```java StatelessKieSession ksession = kbase.newStatelessKieSession(); List cmds = new ArrayList(); cmds.add( CommandFactory.newInsertObject( new Cheese( "stilton", 1), "stilton") ); cmds.add( CommandFactory.newStartProcess( "process cheeses" ) ); cmds.add( CommandFactory.newQuery( "cheeses" ) ); ExecutionResults bresults = ksession.execute( CommandFactory.newBatchExecution( cmds ) ); Cheese stilton = ( Cheese ) bresults.getValue( "stilton" ); QueryResults qresults = ( QueryResults ) bresults.getValue( "cheeses" ); ``` -------------------------------- ### Example Usage of Keywords for Imports, Headers, etc. Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html A comprehensive example showcasing the usage of various column headers, including keywords for imports and attributes that are not applied. ```drools CONDITION --- Person age == $param Persons age 42 ``` ```drools CONDITION --- Person age < Persons age 42 ``` ```drools c : Cheese type Cheese type stilton ``` ```drools list.add("$param"); Log Old man stilton ``` -------------------------------- ### Build and Install KieModule (Maven) Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Use this Maven command to build and install a programmatically generated KieModule. This is part of the default build process. ```bash mvn install Copied! ``` -------------------------------- ### Example Maven Build Output Source: https://docs.drools.org/latest/drools-docs/drools/getting-started/index.html This is an example of the console output after running 'mvn clean verify', showing the test execution status for the TrafficViolationTest. ```text [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running org.example.TrafficViolationTest 2022-08-29 16:11:44,539 [main] INFO Evaluating DMN model 2022-08-29 16:11:44,540 [main] INFO Checking results: DMNResultImpl{context={ Driver: { Points: 2 } Violation: { Type: speed Speed Limit: 100 Actual Speed: 120 } Fine: { Points: 3 Amount: 500 } Should the driver be suspended?: No } , messages=org.kie.dmn.core.util.DefaultDMNMessagesManager@4f89331f} [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 s - in org.example.TrafficViolationTest ``` -------------------------------- ### Example JVM Execution Command Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Illustrates how to execute an application with KIE security policies enabled using JVM parameters. ```bash java -Djava.security.manager -Djava.security.policy=global.policy -Dkie.security.policy=rules.policy foo.bar.MyApp ``` -------------------------------- ### Console Output Example Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Illustrates the output from a stateful KIE session, showing actions taken and the final state. ```text > Cancel the alarm > Turn off the sprinkler for room office > Turn off the sprinkler for room kitchen > Everything is ok ``` -------------------------------- ### Accumulate CE example for order discounts Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Demonstrates using the 'accumulate' CE to calculate the total value of order items for applying discounts. This example uses Java as the semantic dialect and shows how to initialize, accumulate, and retrieve a result. ```drl rule "Apply 10% discount to orders over US$ 100,00" when $order : Order() $total : Number( doubleValue > 100 ) from accumulate( OrderItem( order == $order, $value : value ), init( double total = 0; ), action( total += $value; ), reverse( total -= $value; ), result( total ) ) then // apply discount to $order end Copied! ``` -------------------------------- ### Accumulate CE example with custom objects Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Shows how to use the 'accumulate' CE to instantiate and populate custom objects. This example demonstrates accumulating data from 'Cheese' objects into a 'Cheesery' object. ```drl rule "Accumulate using custom objects" when $person : Person( $likes : likes ) $cheesery : Cheesery( totalAmount > 100 ) from accumulate( $cheese : Cheese( type == $likes ), ``` -------------------------------- ### Register and Start KieScanner with Maven Repository Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html This snippet shows how to register and start a KieScanner to poll a Maven repository at a specified interval. It requires kie-ci.jar on the classpath. ```java KieServices kieServices = KieServices.Factory.get(); ReleaseId releaseId = kieServices.newReleaseId( "org.acme", "myartifact", "1.0-SNAPSHOT" ); KieContainer kContainer = kieServices.newKieContainer( releaseId ); KieScanner kScanner = kieServices.newKieScanner( kContainer ); // Start the KieScanner polling the Maven repository every 10 seconds kScanner.start( 10000L ); ``` -------------------------------- ### Register and Start KIE Scanner Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Register and start a KIE scanner for a KIE container, configuring it to poll the Maven repository at a specified interval. Ensure the 'kie-ci.jar' is on the classpath. The project version must be a SNAPSHOT version. ```java import org.kie.api.KieServices; import org.kie.api.builder.ReleaseId; import org.kie.api.runtime.KieContainer; import org.kie.api.builder.KieScanner; ... KieServices kieServices = KieServices.Factory.get(); ReleaseId releaseId = kieServices .newReleaseId("com.sample", "my-app", "1.0-SNAPSHOT"); KieContainer kContainer = kieServices.newKieContainer(releaseId); KieScanner kScanner = kieServices.newKieScanner(kContainer); // Start KIE scanner for polling the Maven repository every 10 seconds (10000 ms) kScanner.start(10000L); ``` -------------------------------- ### Start KieScanner On-Demand Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Demonstrates how to use the scanNow() method to trigger a KieScanner update on demand, instead of using a fixed time interval. ```java kScanner.scanNow(); ``` -------------------------------- ### Example JSON Response for Approved Loans Source: https://docs.drools.org/latest/drools-docs/drools/migration-guide/index.html Example JSON response showing the list of loan applications that were approved based on the rule evaluation. ```json [ { "id": "ABC10001", "applicant": { "name": "John", "age": 45 }, "amount": 2000, "deposit": 1000, "approved": true } ] ``` -------------------------------- ### Flat Text Output Example Source: https://docs.drools.org/latest/drools-docs/drools/experimental-features/index.html Example of flat text output from TextReporter, listing changed and impacted rules. ```text --- toFlatText --- Inventory shortage[+] PriceCheck_11[*] StatusCheck_11[+] StatusCheck_12[+] StatusCheck_13[+] ``` -------------------------------- ### Query Response Example Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html This is an example of the JSON response received after invoking the '/high-severity' query endpoint. It shows the 'alerts' array containing objects that match the query criteria. ```json { "alerts" : [ { "severity" : "HIGH", "message" : "Temperature exceeds threshold: 100" } ] } ``` -------------------------------- ### String Literal Example Source: https://docs.drools.org/latest/drools-docs/drools/DMN/index.html Demonstrates a basic string literal in FEEL. ```FEEL "John Doe" ``` -------------------------------- ### DSL Expansion Examples Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Demonstrates how the defined DSL rules are expanded into standard DRL syntax. Shows expansion of single and chained conditions. ```drl Person(name="Kitty") ``` ```drl Person(age >= 42, location="Atlanta") ``` ```drl System.out.println("boo"); ``` ```drl Person(name="Bob") and Person(age >= 30, location="Utah") ``` -------------------------------- ### Keyword Definition Example Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Defines a keyword replacement, changing 'regula' to 'rule'. ```dsl [keyword][]regula=rule ``` -------------------------------- ### Example Interval Timer Attributes Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Illustrates the syntax for interval timers in DRL, specifying initial delay and repeat intervals. ```drl // Run after a 30-second delay timer ( int: 30s ) // Run every 5 minutes after a 30-second delay each time timer ( int: 30s 5m ) ``` -------------------------------- ### Maven Settings.xml Profile Activation Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Example of activating a Maven profile by default in settings.xml. This is used for configuring remote repositories. ```xml profile-1 true ... ``` -------------------------------- ### Build KieFileSystem Contents and Create KieContainer Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html This example shows the complete process of building the contents of a KieFileSystem, which automatically adds the resulting KieModule to the KieRepository. It then demonstrates creating a KieContainer using the KieModule's ReleaseId. ```java KieServices kieServices = KieServices.Factory.get(); ``` -------------------------------- ### Get Global Command Example Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Executes a GetGlobal command to retrieve an existing global variable from the session. An optional String argument can specify an alternative return name. ```java StatelessKieSession ksession = kbase.newStatelessKieSession(); ExecutionResults bresults = ksession.execute( CommandFactory.getGlobal( "stilton" ); Cheese stilton = bresults.getValue( "stilton" ); ``` -------------------------------- ### Accessing List Elements by Positive Index Source: https://docs.drools.org/latest/drools-docs/drools/DMN/index.html Elements in a FEEL list can be accessed by index, starting from 1 for the first element. This example retrieves the second element of list 'x'. ```feel x[2] ``` -------------------------------- ### Rule with 'from entry-point' Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Demonstrates using 'from entry-point' to specify a data source for a pattern, often used with event streams. ```java rule "Authorize withdrawal" when WithdrawRequest( $ai : accountId, $am : amount ) from entry-point "ATM Stream" CheckingAccount( accountId == $ai, balance > $am ) then // Authorize withdrawal. end ``` -------------------------------- ### EventA started by EventB Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html This pattern matches if EventA and EventB start at the same time, and EventB ends before EventA ends. This is the reverse behavior of the 'starts' operator. ```java $eventA : EventA(this startedby $eventB) ``` ```java $eventA.startTimestamp == $eventB.startTimestamp && $eventA.endTimestamp > $eventB.endTimestamp ``` -------------------------------- ### Maven Repository Metadata Example Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html This XML snippet shows the metadata structure for a Maven artifact, including versioning information. ```xml com.foo my-foo 2.0.0 1.1.1 1.0 1.0.1 1.1 1.1.1 2.0.0 20090722140000 ``` -------------------------------- ### Conditions for EventA starts EventB Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Specifies the conditions for EventA starting before or at the same time as EventB, and ending before EventB ends: EventA's start timestamp must equal EventB's start timestamp, and EventA's end timestamp must be less than EventB's end timestamp. ```drl $eventA.startTimestamp == $eventB.startTimestamp && $eventA.endTimestamp < $eventB.endTimestamp ``` -------------------------------- ### Legacy DRL Rule Condition Elements Example Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Illustrates the use of init, action, reverse, and result in a legacy DRL rule condition. ```java init( Cheesery cheesery = new Cheesery(); ), action( cheesery.addCheese( $cheese ); ), reverse( cheesery.removeCheese( $cheese ); ), result( cheesery ) ); then // do something end ``` -------------------------------- ### DRL Constraint Example Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html An example of a standard DRL rule condition with multiple field constraints. ```drl Cheese(age < 5, price == 20, type=="stilton", country=="ch") ``` -------------------------------- ### EventA started by EventB within 5 seconds Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html This pattern matches if EventA starts within 5 seconds of EventB, and EventB ends before EventA ends. It requires that the absolute difference between their start timestamps is less than or equal to 5 seconds. ```java $eventA : EventA( this starts[5s] $eventB) ``` ```java abs( $eventA.startTimestamp - $eventB.startTimestamp ) <= 5s && $eventA.endTimestamp > $eventB.endTimestamp ``` -------------------------------- ### Example of Functions for Computing Price and Discount Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Demonstrates the use of Import, Functions, and RuleSet keywords in a decision table to define helper functions for rule execution. ```java function int computePrice(Cheese cheese) { if (cheese.getType() == "cheddar") { return 10; } else if (cheese.getType() == "stilton") { return 15; } else { return 20; } } function boolean hasDiscount(Person person) { if (person.getAge() > 60) { return true; } else { return false; } } ``` -------------------------------- ### Date and Time Construction Examples Source: https://docs.drools.org/latest/drools-docs/drools/DMN/index.html Demonstrates constructing date and time values using the `date and time()` function. Supports formats including timezone offsets and UTC. ```FEEL date and time( "2017-10-22T23:59:00" ) ``` ```FEEL date and time( "2017-06-13T14:10:00+02:00" ) ``` ```FEEL date and time( "2017-02-05T22:35:40.345-05:00" ) ``` ```FEEL date and time( "2017-06-13T15:00:30z" ) ``` -------------------------------- ### EventA starts EventB within 5 seconds Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html This pattern matches if EventA starts within 5 seconds of EventB. It requires that the absolute difference between their start timestamps is less than or equal to 5 seconds, and EventA ends before EventB ends. ```java $eventA : EventA(this starts[5s] $eventB) ``` ```java abs($eventA.startTimestamp - $eventB.startTimestamp) <= 5s && $eventA.endTimestamp < $eventB.endTimestamp ``` -------------------------------- ### Example Cron Timer Attribute Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Shows an example of a cron timer attribute in DRL for scheduling rule execution. ```drl // Run every 15 minutes timer ( cron:* 0/15 * * * ? ) ``` -------------------------------- ### DRL Example: Delete Applicant Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Example of using the `delete` method to remove an `Applicant` object from the Drools rule engine. ```drl delete( Applicant ); ``` -------------------------------- ### Instance Creation Using Key Constructor Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html This example illustrates how to instantiate a fact type using a constructor generated based on the key attributes. This is useful when you want to create objects that are uniquely identified by their key fields. ```java Person person = new Person( "John", "Doe" ); ``` -------------------------------- ### Hierarchy Text Output Example Source: https://docs.drools.org/latest/drools-docs/drools/experimental-features/index.html Example of hierarchy text output from TextReporter, indicating changed rules with [*] and impacted rules with [+]. ```text --- toHierarchyText --- Inventory shortage[+] PriceCheck_11[*] StatusCheck_12[+] (Inventory shortage) StatusCheck_13[+] StatusCheck_11[+] (PriceCheck_11) ``` -------------------------------- ### Time Construction Examples Source: https://docs.drools.org/latest/drools-docs/drools/DMN/index.html Illustrates constructing time values using the `time()` function in FEEL. Supports various formats including time with timezone offsets and UTC. ```FEEL time( "04:25:12" ) ``` ```FEEL time( "14:10:00+02:00" ) ``` ```FEEL time( "22:35:40.345-05:00" ) ``` ```FEEL time( "15:00:30z" ) ``` -------------------------------- ### Creating, Setting, Updating, and Clearing SingletonStore Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Shows how to use a SingletonStore to manage a single 'Measurement' object. Demonstrates setting, updating, and clearing the value, with notifications. ```java SingletonStore measurement = DataSource.createSingleton(); Measurement m1 = new Measurement("color", "red"); // Add value `m1` and notify all subscribers measurement.set(m1); measure.setValue("blue"); // Notify all subscribers that the value has changed measurement.update(); Measurement m2 = new Measurement("color", "green"); // Overwrite contained value with `m2` and notify all subscribers measurement.set(m2); measure2.setValue("black"); // Notify all subscribers that the value has changed measurement.update(); // Clear store and notify all subscribers measurement.clear(); ``` -------------------------------- ### DRL Example: Insert New Applicant Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Example of using the `insert` method to add a new `Applicant` object to the working memory. ```drl insert( new Applicant() ); ``` -------------------------------- ### Days and Time Duration Construction Examples Source: https://docs.drools.org/latest/drools-docs/drools/DMN/index.html Shows how to construct days and time duration values using the `duration()` function. Supports ISO 8601 format for days, hours, minutes, and seconds. ```FEEL duration( "P1DT23H12M30S" ) ``` ```FEEL duration( "P23D" ) ``` ```FEEL duration( "PT12H" ) ``` ```FEEL duration( "PT35M" ) ``` -------------------------------- ### DRL Example: Update Loan Application Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Example of using the `update` method to change the amount of a loan application fact and then notify the engine. ```drl $application.setAmount( 100 ); update( $application ); ``` -------------------------------- ### DRL Example: Modify Loan Application Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Example of using the `modify` method to update the amount and approval status of a loan application fact. ```drl modify( $application ) { setAmount( 100 ), setApproved ( true ) } ``` -------------------------------- ### Implement DRL File with Standard DRL Syntax Source: https://docs.drools.org/latest/drools-docs/drools/migration-guide/index.html Alternatively, use standard DRL syntax to specify the data source as an entry point. The object type must be explicitly stated. ```drl $l: LoanApplication( applicant.age >= 20, deposit >= 1000, amount ⇐ maxAmount ) from entry-point loanApplications ``` -------------------------------- ### Date Construction Example Source: https://docs.drools.org/latest/drools-docs/drools/DMN/index.html Shows how to construct a date value using the built-in `date()` function in FEEL. Dates follow the 'YYYY-MM-DD' format. ```FEEL date( "2017-06-23" ) ``` -------------------------------- ### Example ReteDumper Output Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Shows sample output from ReteDumper, mapping node identifiers to rule names. This helps in pinpointing which rule corresponds to a performance metric. ```text [ AccumulateNode(8) ] : [Collect expensive orders combination] ... ``` -------------------------------- ### DRL Example: Logically Insert New Applicant Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Example of using the `insertLogical` method to add a new `Applicant` object logically to the working memory. ```drl insertLogical( new Applicant() ); ``` -------------------------------- ### Sample kmodule.xml Configuration Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Defines two KieBases with different configurations and multiple KieSessions, including custom operators, listeners, and work item handlers. ```xml ``` -------------------------------- ### Example cURL Request to Find Approved Loans Source: https://docs.drools.org/latest/drools-docs/drools/migration-guide/index.html Example cURL command to invoke the REST endpoint with JSON payload for loan application evaluation. ```bash curl -X POST -H 'Accept: application/json' -H 'Content-Type: application/json' -d '{"maxAmount":5000, "loanApplications":[ {"id":"ABC10001","amount":2000,"deposit":1000,"applicant":{"age":45,"name":"John"}}, {"id":"ABC10002","amount":5000,"deposit":100,"applicant":{"age":25,"name":"Paul"}}, {"id":"ABC10015","amount":1000,"deposit":100,"applicant":{"age":12,"name":"George"}} ]}' http://localhost:8080/find-approved ``` -------------------------------- ### MVEL Invalid Coercion Example (Non-Executable Model) Source: https://docs.drools.org/latest/drools-docs/drools/migration-guide/index.html Shows an example where the non-executable model coerces an int to a Long, which would fail in the executable model. ```java rule Rule1 dialect "mvel" when $f : Fact() then $f.setWrapperLong(10); end ``` -------------------------------- ### EventA starts EventB Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Matches if EventA and EventB start at the same time, and EventA ends before EventB ends. This operator can also be expressed using timestamp comparisons. ```drl $eventA : EventA(this starts $eventB) ``` -------------------------------- ### Execute Stateless Session with Commands Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Shows how to use CommandFactory to create and execute a list of commands, such as inserting multiple Person objects into the session. ```java List cmds = new ArrayList(); __**(3)** cmds.add(CommandFactory.newInsert(new Person("Mr John Smith"), "mrSmith")); cmds.add(CommandFactory.newInsert(new Person("Mr John Doe"), "mrDoe")); ``` -------------------------------- ### Instantiate and Execute a Rule Unit Instance Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Use `RuleUnitProvider` to create a `RuleUnitInstance` for executing rules. Remember to dispose of the instance when done. ```java public void test() { MeasurementUnit measurementUnit = new MeasurementUnit(); RuleUnitInstance instance = RuleUnitProvider.get().createRuleUnitInstance(measurementUnit); try { measurementUnit.getMeasurements().add(new Measurement("color", "red")); ... List queryResult = instance.executeQuery("FindColor").stream().map(tuple -> (Measurement) tuple.get("$m")).collect(toList()); ... } finally { instance.dispose(); } } ``` -------------------------------- ### Example calendar attributes Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html These examples show how to use the 'calendars' attribute with a Quartz cron expression to exclude non-business hours or use a pre-registered calendar name. ```drl // Exclude non-business hours calendars "* * 0-7,18-23 ? * *" ``` ```drl // Weekdays only, as registered in the KIE session calendars "weekday" ``` -------------------------------- ### Execute Rule Unit Instance Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html This snippet shows how to instantiate a RuleUnit, add data, create a RuleUnitInstance, fire rules, and assert the results. It demonstrates the runtime execution of rules defined via the Rule Unit DSL. ```java public void helloWorld() { HelloWorldUnit unit = new HelloWorldUnit(); unit.getStrings().add("Hello World"); RuleUnitInstance unitInstance = RuleUnitProvider.get().createRuleUnitInstance(unit); assertThat(unitInstance.fire()).isEqualTo(2); assertThat(unit.getResults()).containsExactlyInAnyOrder("it worked!", "it also worked with HELLO WORLD"); unit.getResults().clear(); unit.getInts().add(11); assertThat(unitInstance.fire()).isEqualTo(1); assertThat(unit.getResults()).containsExactly("String 'Hello World' is 11 characters long"); unitInstance.close(); } ``` -------------------------------- ### Register and Start KieScanner with File System Repository Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html This snippet illustrates how to configure a KieScanner to monitor a local file system folder for kjar updates. The folder must contain jar files named according to the Maven convention. ```java KieServices kieServices = KieServices.Factory.get(); KieScanner kScanner = kieServices.newKieScanner( kContainer, "/myrepo/kjars" ); ``` -------------------------------- ### EventA met by EventB Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Matches if EventB ends at the same time EventA starts. This is the reverse of the 'meets' operator. It supports an optional time parameter for the maximum distance between the end of EventB and the start of EventA. ```drl $eventA : EventA(this metby $eventB) ``` -------------------------------- ### Timer attribute with start, end, and repeat-limit Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html This snippet shows a timer attribute with optional start, end, and repeat-limit parameters. The timer will stop when either the end date is reached or the repeat limit is met. ```drl timer (int: 30s 1h; start=3-JAN-2020, end=4-JAN-2020, repeat-limit=50) ``` -------------------------------- ### Application Code for Live Query with Event Listener Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Sets up a ViewChangedEventListener to monitor updates, removals, and additions to a live query. It then opens the 'colors' live query with specific parameters ('red', 'blue') and demonstrates how to dispose of the query. ```java final List updated = new ArrayList(); final List removed = new ArrayList(); final List added = new ArrayList(); ViewChangedEventListener listener = new ViewChangedEventListener() { public void rowUpdated(Row row) { updated.add( row.get( "$price" ) ); } public void rowRemoved(Row row) { removed.add( row.get( "$price" ) ); } public void rowAdded(Row row) { added.add( row.get( "$price" ) ); } }; // Open the live query: LiveQuery query = ksession.openLiveQuery( "colors", new Object[] { "red", "blue" }, listener ); ... ... // Terminate the live query: query.dispose() ``` -------------------------------- ### EventA meets EventB Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Matches if EventA ends at the same time EventB starts. This operator can also accept an optional time parameter to define the maximum allowed time between the end of EventA and the start of EventB. ```drl $eventA : EventA(this meets $eventB) ``` -------------------------------- ### Utilize and Run KieModule with Meta Models (Java) Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html This Java code demonstrates building a KieModule by defining its kmodule.xml meta-model programmatically. It includes setting up ReleaseIds, generating POM XML, defining KieBases and KieSessions, and then building and running the module. ```java KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem(); Resource ex1Res = ks.getResources().newFileSystemResource(getFile("named-kiesession")); Resource ex2Res = ks.getResources().newFileSystemResource(getFile("kiebase-inclusion")); ReleaseId rid = ks.newReleaseId("org.drools", "kiemodulemodel-example", "6.0.0-SNAPSHOT"); kfs.generateAndWritePomXML(rid); KieModuleModel kModuleModel = ks.newKieModuleModel(); kModuleModel.newKieBaseModel("kiemodulemodel") .addInclude("kiebase1") .addInclude("kiebase2") .newKieSessionModel("ksession6"); kfs.writeKModuleXML(kModuleModel.toXML()); kfs.write("src/main/resources/kiemodulemodel/HAL6.drl", getRule()); KieBuilder kb = ks.newKieBuilder(kfs); b.setDependencies(ex1Res, ex2Res); b.buildAll(); // kieModule is automatically deployed to KieRepository if successfully built. if (kb.getResults().hasMessages(Level.ERROR)) { throw new RuntimeException("Build Errors:\n" + kb.getResults().toString()); } KieContainer kContainer = ks.newKieContainer(rid); KieSession kSession = kContainer.newKieSession("ksession6"); kSession.setGlobal("out", out); Object msg1 = createMessage(kContainer, "Dave", "Hello, HAL. Do you read me, HAL?"); kSession.insert(msg1); kSession.fireAllRules(); Object msg2 = createMessage(kContainer, "Dave", "Open the pod bay doors, HAL."); kSession.insert(msg2); kSession.fireAllRules(); Object msg3 = createMessage(kContainer, "Dave", "What's the problem?"); kSession.insert(msg3); kSession.fireAllRules(); javaCopied! ``` -------------------------------- ### Event A occurs before Event B with time range Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Matches if EventA finishes between 3m30s and 4m before EventB starts. This pattern is not matched if EventA finishes earlier than 3m30s or later than 4m before EventB starts. ```java $eventA : EventA(this before[3m30s, 4m] $eventB) ``` -------------------------------- ### Instantiate Stateful KieSession and Insert Initial Data Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Creates a new stateful KieSession from the KieContainer and inserts initial room and sprinkler facts. ```java KieSession ksession = kContainer.newKieSession(); String[] names = new String[]{"kitchen", "bedroom", "office", "livingroom"}; Map name2room = new HashMap(); for( String name: names ){ Room room = new Room( name ); name2room.put( name, room ); ksession.insert( room ); Sprinkler sprinkler = new Sprinkler( room ); ksession.insert( sprinkler ); } ksession.fireAllRules(); ``` -------------------------------- ### Event A occurs after Event B with time range Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Matches if EventA starts between 3m30s and 4m after EventB finishes. This pattern is not matched if EventA starts earlier than 3m30s or later than 4m after EventB finishes. ```java $eventA : EventA(this after[3m30s, 4m] $eventB) ``` -------------------------------- ### Build Maven Project Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Builds the Maven project to generate a JAR file in the target folder, which can then be referenced as a File resource. ```bash mvn install Copied! ``` -------------------------------- ### Build Drools with Tests Source: https://docs.drools.org/latest/drools-docs/drools/introduction/index.html Run this command to build the Drools project and execute all associated tests. ```bash mvn clean install ``` -------------------------------- ### Event Includes Another Event's Timeframe Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Checks if event $eventA's time frame completely encompasses event $eventB. The start and end times of $eventB must fall between the start and end times of $eventA. ```drools $eventA : EventA(this includes $eventB) ``` ```drools $eventA.startTimestamp < $eventB.startTimestamp <= $eventB.endTimestamp < $eventA.endTimestamp ``` -------------------------------- ### Build KieModule with Impact Analysis Source: https://docs.drools.org/latest/drools-docs/drools/experimental-features/index.html Create a KieFileSystem, build the KieModule using KieBuilder, and specify ImpactAnalysisProject.class to obtain the AnalysisModel. ```java // set up KieFileSystem ... KieBuilder kieBuilder = KieServices.Factory.get().newKieBuilder(kfs).buildAll(ImpactAnalysisProject.class); ImpactAnalysisKieModule analysisKieModule = (ImpactAnalysisKieModule) kieBuilder.getKieModule(); AnalysisModel analysisModel = analysisKieModule.getAnalysisModel(); ``` -------------------------------- ### Configure Default KieSession with kmodule.xml Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html An empty kmodule.xml file is used to create a default KieBase that includes all resources on the classpath. This is useful when you have a single KieBase and want to access its default KieSession without explicit naming. ```xml ``` -------------------------------- ### EventA overlaps EventB Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Matches if EventA starts before EventB and ends while EventB is occurring, but before EventB ends. This operator can take one or two parameters to define the maximum or a range of distances between EventB's start and EventA's end. ```drl $eventA : EventA(this overlaps $eventB) ``` -------------------------------- ### KIE Base Configuration Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Example configuration for a KIE base in a kmodule.xml file. This defines a KIE base named 'KBase2' with specific packages and includes another KIE base. ```xml ... ... ... ``` -------------------------------- ### Event Contained Within Another Event's Timeframe Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Checks if event $eventA occurs entirely within the time frame of event $eventB. The start and end times of $eventA must fall between the start and end times of $eventB. ```drools $eventA : EventA(this during $eventB) ``` ```drools $eventB.startTimestamp < $eventA.startTimestamp <= $eventA.endTimestamp < $eventB.endTimestamp ``` -------------------------------- ### EventA met by EventB with time constraint Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Matches if EventA starts within 5 seconds of EventB ending. The absolute difference between EventA's start timestamp and EventB's end timestamp must be less than or equal to 5 seconds. ```drl $eventA : EventA(this metby[5s] $eventB) ``` -------------------------------- ### Java Application with EntryPoint Object Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html This Java code demonstrates how to obtain an EntryPoint object from a KieSession and insert facts into a specific entry point named 'ATM Stream'. Rules referencing this entry point will then evaluate against these inserted facts. ```java import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.EntryPoint; // Create your KIE base and KIE session as usual. KieSession session = ... // Create a reference to the entry point. EntryPoint atmStream = session.getEntryPoint("ATM Stream"); // Start inserting your facts into the entry point. atmStream.insert(aWithdrawRequest); ``` -------------------------------- ### EventA meets EventB with time constraint Source: https://docs.drools.org/latest/drools-docs/drools/rule-engine/index.html Matches if EventA ends within 5 seconds of EventB starting. The absolute difference between EventB's start timestamp and EventA's end timestamp must be less than or equal to 5 seconds. ```drl $eventA : EventA(this meets[5s] $eventB) ``` -------------------------------- ### Execute Collection with InsertElements Command Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html This snippet demonstrates executing a collection by wrapping it in an InsertElements command for the StatelessKieSession. ```java ksession.execute( CommandFactory.newInsertElements( collection ) ); ``` -------------------------------- ### Creating a KieContainer from the Classpath Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html To trigger the building of Kie artifacts, create a KieContainer. This example shows how to create a KieContainer that reads files to be built from the classpath. ```java KieServices kieServices = KieServices.Factory.get(); KieContainer kContainer = kieServices.getKieClasspathContainer(); ``` -------------------------------- ### Example DRL Rule Unit File for Loan Application Source: https://docs.drools.org/latest/drools-docs/drools/language-reference/index.html Declares a Drools rule unit named MortgageRules, imports necessary APIs, defines data stores for fact types, and includes two example rules: 'Bankruptcy history' and 'Underage'. ```drl package org.mortgages; unit MortgageRules; import org.drools.ruleunits.api.RuleUnitData; import org.drools.ruleunits.api.DataStore; declare MortgageRules extends RuleUnitData bankruptcies: DataStore applicants: DataStore loanApplications: DataStore end rule "Bankruptcy history" salience 10 when $a : /loanApplications[ applicantName: applicant ] exists (/bankruptcies[ name == applicantName, yearOfOccurrence > 1990 || amountOwed > 100000 ]) then $a.setApproved( false ); $a.setExplanation( "has been bankrupt" ); loanApplications.remove( $a ); end rule "Underage" salience 15 when /applicants[ applicantName : name, age < 21 ] $application : /loanApplications[ applicant == applicantName ] then $application.setApproved( false ); $application.setExplanation( "Underage" ); loanApplications.remove( $a ); end ``` -------------------------------- ### Creating, Adding, Updating, and Removing from DataStore Source: https://docs.drools.org/latest/drools-docs/drools/KIE/index.html Illustrates the usage of DataStore for managing 'Measurement' objects. Includes adding, updating, and removing data, with notifications to subscribers. ```java DataStore measurements = DataSource.createStore(); Measurement measurement = new Measurement("color", "red"); // Add value and notify all subscribers DataHandle mHandle = measurements.add(measurement); measure.setValue("blue"); // Notify all subscribers that the value referenced by `mHandle` has changed measurements.update(mHandle, measurement); // Remove value referenced by `mHandle` and notify all subscribers measurements.remove(mHandle); ```