Software Engineering Section

Transkrypt

Software Engineering Section
Software Engineering Section
Enterprise Informatization
LECTURE
Piotr Zabawa, PhD. Eng.
IBM/Rational Certified Consultant
e-mail: [email protected]
www:
http://www.pk.edu.pl/~pzabawa/en
07.10.2011
Software Engineering Section
Lecture 4
Business events mechanism
in Jboss Drools environment
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Introduction
In order to better understand pratical importance of the
business event notion we will make use of simplified (but not
very simple) examples DroolsHelloWorld 05-08.
These samples were invented by the author of the lecture.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Introduction
All mentioned DroolsHelloWorld examples are connected
to greeting and show one by one how to:
• Trigger an activity (greeting) by business event
• Calculate the authority of a whole group of people
measured by average value of all greetings addressed to its
members using appropriate query (used in next example)
• Calculate the authorities of each group member measured
by average greetings sentece lenght addressed to this
memeber.
• Access Drools native object data from Java source code
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
We will discuss the following topics iluustarting them by
DroolsHelloWorld examples:
• How to define an event
• How to send an event
• How to tunell events flow – memory organization
• How to use events in rules
• How to conduct statistical analysis of events independently
on time
• How to share statistical data between rules
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
Facts constitute static data, but usually in business process
modeling there is a need of definition of time-related relation
between facts. This approach is known as Complex Event
Processing (CEP) or Event Stream Processing (ESP). The
Drools Fusion supports this approach.
For now we will be focused on events not related to time
axe, which means that the order of events as well as specific
sequences in time will not be interesting for us.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
The approach connected to events processing is related to
the notion of Event Driven Architecture. It is worth making
familiar with it (out of this year lecture scope).
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
An event consists of:
• Header containing meta-data (name, submission time,
lasting time,…)
• Body containing domain-specific information about an
event (UUID of bank transaction, bank transfer value,
source account, target account,…)
CEP notion is associated to event sequences, but not to
single events.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
DroolsHelloWorld_05
This example shows how to create, send and catch an event.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
What is an event?
Java POJO class possibly with final private fields (the
event should not be change!) setting in the constructor only:
public class NotificationEvent implements Serializable {
private static final long serialVersionUID = 1L;
public NotificationEvent(){
}
@Override
public String toString(){
return null;
}
}
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
Event is a special kind of fact, that should be also placed in
the business rules engine session. The rule could be as
follows:
// modyfikacja istniejącego faktu
declare NotificationEvent
@role( event )
end
rule "Event notification"
when
NotificationEvent()
from entry-point NotificationStream;
then
System.out.println( "Hello World!" );
end
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
What is an entry point?
Memory could/should be divided int event streams – it
gives a chance of separation of event groups and the
possibility of better use of parallel event processing
mechanisms implemented in business rules engine.
The entry-point joins an event with an event stream we
want to associate it.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
How to place an event in sesion?
Before knowledge base creation:
KnowledgeBaseConfiguration config =
KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
config.setOption(EventProcessingOption.STREAM);
After knowledge base creation:
WorkingMemoryEntryPoint entry =
ksession.getWorkingMemoryEntryPoint("NotificationStream");
entry.insert(new NotificationEvent());
ksession.fireAllRules();
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
DroolsHelloWorld_06
Shows how to define a query in Drools for statistical
analysis and how to get access to query result from Java
source code. Such a query can be used for events statistical
analysis, but in this example events are not used for that.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
Statistical calculation could be used for calculating group
of people prestige measured by average length of greeting
sentences addressed to group members – one average value
for the whole group.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
The following query will be used for calculation of the
statistical characteristics of the group:
query "averagePrestigeQuery"
Number( $averagePrestige : doubleValue ) from accumulate(
$receiver : GreetingsReceiver(),
average($receiver.getLength()))
end
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
Inside collect or accumulate the following
operators can be used:
• count
• min
• max
• sum
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
GreetingsReceiver tomek = new GreetingsReceiver("Tomek");
ksession.insert(tomek);
tomek.receiveGreeting("Hi");
GreetingsReceiver janek = new GreetingsReceiver("Janek");
ksession.insert(janek);
janek.receiveGreeting("Hello");
GreetingsReceiver staszek = new GreetingsReceiver("Staszek");
ksession.insert(staszek);
staszek.receiveGreeting("Good morning");
ksession.fireAllRules();
System.out.println(getAveragePrestige(ksession));
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
The method for obtaining the query result(s):
private static BigDecimal
getAveragePrestige(StatefulKnowledgeSession ksession){
QueryResults queryResults =
ksession.getQueryResults("averagePrestigeQuery");
return BigDecimal.valueOf((Double)
queryResults.iterator().next().get("$averagePrestige")
);
}
Data conversion and different ways of query object and
query value object (do not forget to use $ singn in the last
case!) access are underlined above.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
DroolsHelloWorld_07
Shows how to calculate average lenght of greeting
sentences addressed to people group members per each
member. This statistical result could be used as a measure of
each member prestige in the group. The shared Drools native
class can be also shown.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
Native Drools data type that can be shared between
business rules is presented below. Their objects will be
created from Java code and passed from one rule to the other.
So, in our example the following Drools native data type is
defined:
declare GreetingsInfo
name: String
averageLength: Double
end
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Types of fields were chosen
to avoid conversion
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
In order to show communication between rules with
application of shared data the following two rules are
implemented:
• The first rule calculates average values per one people and
writes these results into native Drools objects
• The second rule makes use of the statistical data calculated
and stored by the first rule in native Drools objects and
writes these results into console (shared objects are used in
rule conditions)
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
// the rule calculates average greeting length
rule "Average greetings length"
dialect "mvel"
no-loop true
when
$receiver : GreetingsReceiver()
$averageLength : Double() from accumulate(
GreetingReceivedEvent(receiver == $receiver.name)
from entry-point GreetingsStream,
average($receiver.getLength()) )
$greetingsInfo : GreetingsInfo(name == $receiver.name)
then
modify($greetingsInfo){
setAverageLength($averageLength)
};
end
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
// the rule makes use of calculated values
// it prints the name of each group member
// together with the value of average greeting length
// calculated for him
rule "Report greetings"
dialect "mvel"
when
$info : GreetingsInfo()
then
System.out.println( "name = "+$info.name );
System.out.println( "average = "
+$info.getAverageLength() );
end
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
public class GreetingsReceiver {
private String name;
private String greetings = "";
public GreetingsReceiver(String name){
this.name = name;
}
public String getName(){
return name;
}
public void receiveGreeting(String greeting){
greetings = greeting;
}
@Override
public boolean equals(final Object other){
if (this==other) return true;
if (!(other instanceof GreetingsReceiver)) return false;
GreetingsReceiver castOther = (GreetingsReceiver) other;
return name.equals(castOther.name);
}
public long getLength(){
long counter = 0;
for (int i=0; i<greetings.length(); i++)
if (greetings.charAt(i) != ' ') counter++;
return counter;
}
}
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
public class GreetingReceivedEvent implements Serializable {
private static final long serialVersionUID = 1L;
private final String receiver;
public GreetingReceivedEvent(GreetingsReceiver receiver, String greeting){
this.receiver = receiver.getName();
receiver.receiveGreeting(greeting);
}
public String getReceiver(){
return receiver;
}
@Override
public String toString(){
return null;
}
}
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
FactType greetingsInfoFactType = kbase.getFactType("com.sample", "GreetingsInfo");
// insertion of greeting receivers
// and native Drools object for each receiver statistics storage
// into the session
GreetingsReceiver tomek = new GreetingsReceiver("Tomek");// 2
ksession.insert(tomek);
Object greetingsInfoTomek = greetingsInfoFactType.newInstance();
greetingsInfoFactType.set(greetingsInfoTomek, "name", tomek.getName());
greetingsInfoFactType.set(greetingsInfoTomek, "averageLength", 0.0);
ksession.insert(greetingsInfoTomek);
GreetingsReceiver janek = new GreetingsReceiver("Janek");// 8
ksession.insert(janek);
Object greetingsInfoJanek = greetingsInfoFactType.newInstance();
greetingsInfoFactType.set(greetingsInfoJanek, "name", janek.getName());
greetingsInfoFactType.set(greetingsInfoJanek, "averageLength", 0.0);
ksession.insert(greetingsInfoJanek);
GreetingsReceiver staszek = new GreetingsReceiver("Staszek");// 6
ksession.insert(staszek);
Object greetingsInfoStaszek = greetingsInfoFactType.newInstance();
greetingsInfoFactType.set(greetingsInfoStaszek, "name", staszek.getName());
greetingsInfoFactType.set(greetingsInfoStaszek, "averageLength", 0.0);
ksession.insert(greetingsInfoStaszek);
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
// insertion of different greeting events into the session
// addressed to different people
// the average greeting length = (2+5+11)/3 = 6;
String shortGreeting = "Hi";
// 2
String mediumGreeting = "Hello";
// 5
String longGreeting = "Good morning"; // 11
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
WorkingMemoryEntryPoint entry =
ksession.getWorkingMemoryEntryPoint("GreetingsStream");
// events submission
entry.insert(new GreetingReceivedEvent(tomek, shortGreeting));
entry.insert(new GreetingReceivedEvent(janek, mediumGreeting));
entry.insert(new GreetingReceivedEvent(janek, longGreeting));
entry.insert(new GreetingReceivedEvent(staszek, shortGreeting));
entry.insert(new GreetingReceivedEvent(staszek, mediumGreeting));
entry.insert(new GreetingReceivedEvent(staszek, longGreeting));
ksession.fireAllRules();
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
The result of example program execution in console:
name = Staszek
average = 6.0
name = Janek
average = 8.0
name = Tomek
average = 2.0
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
Drools Fusion offers an option of working with events in
connection with the time scale.
It can be done by definition of time frames. A sample
application of this approach in banking domain is detection of
suspicious transactions (ATM withdrawals or bank transfers).
The goal is to find such transaction that can be met in case of
the usage of stolen creadit card or in case of hacking the bank
customer’s pasword in a web bank service.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
rule twoLargeWithdrawals
dialect „mvel”
when
$account : Account()
Number($averageAmount : doubleValue) from accumulate(
TransactionCompletedEvent(fromAccountNumber ==
$account.number, $ammount : ammount)
over window:time(30d) from entry-point
TransactionStream, average($ammount))
$t1 : TransactionCreatedEvent(fromAccountNumber ==
$account.number, amount > ($averageAmmount * 3.00)) over
window:time(90s) from entry-point TransactionStream
$t2 : TransactionCreatedEvent(this!=$t1,
fromAccountNumber ==
$account.number, amount > ($averageAmmount * 3.00)) over
window:time(90s) from entry-point TransactionStream
then…
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
There are two kinds of frames in Drools:
• sliding time window (only for those events that were
submitted in a particular time period)
• sliding length window (only last N events)
They are used for maching only these events that were
started in the frame.
Additionally in case of STREAM mode Drools removes
the events that are not in frame.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
Drools Fusion offers an option of chacking the order of
events submission:
this
after[0, 3m] $t1
The $t1 event started no later then the analysed event started.
This kind of operator is called a temporal operator.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
Besides frames we can use timers in Drools:
• Real-time clock (dedicated for final aplications)
• Pseudo clock (for testing purposes due to full control over
it)
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
The following built-in class families can be used for testing
purposes:
• AgendaEventListener
• AgendaFilter
private void assertFired(String ruleName){
session.fireAllRules(new RuleNameEqualsAgendaFilter(ruleName));
assertTrue(trackingAgendaEventLitener.isRuleFired(ruleName))
}
where:
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
public class TrackingAgendaListener extends DefaultAgendaListener{
List<String> rulesFiredList = new ArrayList<String>();
@Override
public void afterActivationFired(AfterActivationFiredEvent event){
rulesFiredList.add(event.getActivation().getRule().getName());
}
public boolean isRuleFired(String ruleName){
for(String firedRuleName : rulesFiredList)
if(firedRuleName.equals(ruleName)) return true;
return false;
}
public void reset(){
rulesFiredList.clear();
}
}
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
Drools events
The next example, this time coneccted directly to CEP
(event sequences in time) could be a decision of transfer one
person from a group which does not accept him into other
group. As the measure of acceptance the frequency of
greetings addressed to this person can be used. The
assumption here is that too frequent greeting constitute a form
of joke. Also too rare greetings could reflect the lack of
respect.
Pokusimy się więc o napisanie programu, który ustali
regułę eliminacji, a następnie przetestujemy go.
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science
Software Engineering Section
The end
Piotr Zabawa, PhD. Eng.
Institute of Computer Science
Department of Physics, Mathematics and Computer Science

Podobne dokumenty