public
Created

Mule Drools CEP Example

  • Download Gist
broker.drl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
package org.drools.examples.broker
 
import org.mule.MessageExchangePattern;
import org.mule.example.cep.Company
import org.mule.example.cep.StockTick
 
global org.mule.module.bpm.MessageService mule;
 
# default dialect for the semantic code will be MVEL
dialect "mvel"
 
# tells the engine that a StockTick instance will assume the
# role (semantics) of events and that the default retention
# policy will be 2 minutes
declare StockTick
@role( event )
@expires( 2m )
end
 
# One can even declare helper facts to make rules easier and
# simpler to write and maintain
declare Statistics
symbol : String @key()
average : double
end
 
# Default alert threshold, this can be updated at run-time
rule "Setup alert threshold"
when
not( Double() )
then
Double t = new Double(0.07);
insert ( t );
end
 
rule "Setup statistics"
when
$c : Company( $s : symbol )
not( Statistics( symbol == $s ) )
then
Statistics s = new Statistics();
s.symbol = $s;
insert( s );
end
 
# a simple rule to show that it is possible to join
# events from an entry-point (stream) with facts
# present in the working memory
rule "Update stock price"
lock-on-active
 
when
$cp : Company( $sb : symbol )
$st : StockTick( symbol == $sb, $pr : price ) from entry-point "StockTick stream"
then
// This shows an update on working memory facts with data from joined events
modify( $cp ) { currentPrice = $pr }
 
// Although events are considered immutable, a common pattern is to use a class
// to represent an event and enrich that event instance with data derived from other facts/events.
// Bellow we "enrich" the event instance with the percentual change in the price,
// based on the previous price
modify( $st ) { delta = Math.abs($cp.delta) }
end
 
# this rule shows a trick to get the last available event as well as
# how to call global services from the consequence
rule "sudden drop"
salience -10
when
$threshold : Double()
$st : StockTick( $sb : symbol, $ts : timestamp, $pr : price, $dt : delta >= $threshold ) from entry-point "StockTick stream"
not( StockTick( symbol == $sb, timestamp > $ts ) from entry-point "StockTick stream" )
then
msg = "delta > " + StockTick.percent($threshold) + " : " + $sb + " $" + $pr + " (" + StockTick.percent($dt) + ")";
mule.generateMessage("alerts", msg, null, MessageExchangePattern.ONE_WAY);
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.