Anda di halaman 1dari 5

5/4/2015

DroolsexamplejBPM5

Mastertheboss.com
Home

JBoss AS

BPM

JBOSS TRAINING

Projects

Java EE

IDE

SOA-Cloud

DEVELOP APPS

Widest choice of
JBoss/WildFly Training!

Web

JBOSS BOOKS

Start developing Java EE


applications

Learn all about


WildFly/JBoss AS !

FOLLOW US
Follow us on Twitter!
@mastertheboss

Drools example jBPM 5


Drools example jBPM 5
drools example
All Pages

Softwarede
distribucin
SolucinERPpara
manufactura&servicios.
VeaelTourahora!

This tutorial shows how you can easily plug business rules into jBPM 5 processes, and how to handle the
interactions between process and rules.

Business processes and rules are two core concepts which should be stressed out:
Business processes: Represent what the business does.
Business rules: Represent decisions that the business does.
So, although processes and rules are two different thing, there is a clear advantage if your end users are allowed to combine
processes and rules. This means for example that:
rules can define which processes to invoke,
rules can specify decisions in that process
rules can augment (or even override) the behaviour specified in the process (for example to handle exceptional cases)
assignment rules can be used to assign actors to (human) tasks
rules can be used to dynamically alter the behaviour of your process

So, by delegating important decision to be taken into your rules system, your business processes become much more
resilient to change.
jBPM 5 provides a different computational model for business process and rule. This model is based on a knowledgeoriented approach, where the application is not process-oriented or rules-oriented, but the end users can simply select
between different paradigms to represent their business logic. All tools and interfaces the user is confronted with support
this idea of a unified environment throughout the entire knowledge life cycle.
In order to get started, you need to have installed Eclipse jBPM and Drools plugin, you can find instructions on this jBPM 5
tutorial:

http://www.mastertheboss.com/jbossjbpm/drools/droolsexamplejbpm5?showall=1

1/5

5/4/2015

DroolsexamplejBPM5
Now create a new jBPM 5 project which will buy us a minimal bpmn 2.0 project and a Test Class.

Next, add a new Drool resource to your src/main/resources folder, which is in the Test client classpath:

In this very simple rule, we will check a model class (Account) against some validation properties.
The first rule is trivial: we just check that the name property of the Account class is not null:
package samplerule
import com.sample.Account;
rule "nameRequired"
when
$account : Account( name == null )
then
System.out.println( "Account name cannot be null!");
end
Now add the Account class to your project:
1
2
3
4

packagecom.sample;

publicclassAccount{
privatelongmoney;

http://www.mastertheboss.com/jbossjbpm/drools/droolsexamplejbpm5?showall=1

2/5

5/4/2015

DroolsexamplejBPM5
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

privateStringname;

//gettersandsettersomittedforbrevity

@Override
publicStringtoString(){
return"Account[money="+money+",name="+name+"]";
}

publicAccount(){

Good. Now add this simple class to your project (or replace the built-in example test class):
package com.sample;
{codecitation class="brush: java; gutter: true; highlight: [18,20,27,28]"}
import org.drools.KnowledgeBase;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;
public class ProcessMain {

Javato
.NET
Bridge
TheFastest
AndThe
Most
Reliable
Javato
.NETBridge
Ever
Created!

FreeTrial!

public static final void main(String[] args) throws Exception {


// load up the knowledge base
KnowledgeBase kbase = readKnowledgeBase();
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
// start a new process instance

ksession.startProcess("com.sample.bpmn.hello");

ksession.insert(new Account());

ksession.fireAllRules();
}

private static KnowledgeBase readKnowledgeBase() throws Exception {


KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource(
"simplerule.drl"), ResourceType.DRL);
kbuilder.add(ResourceFactory.newClassPathResource("sample.bpmn"), ResourceType.BPMN2);
if (kbuilder.hasErrors()) {
throw new RuntimeException(kbuilder.getErrors()
.toString());
}
KnowledgeBase kbase = kbuilder.newKnowledgeBase();
kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
return kbase;
}

}{/codecitation}
The most interesting part for is is into the readKnowledgeBase() method. There a new KnowledgeBuilder is created and our
rule file is passed into its add method. The rule file is read from the classpath and translated to a Resource newClassPathResource("simplerule.drl").
Alternatively, the rule file can be loaded from an ordinary URL, a byte array,java.io.InputStream, java.io.Reader (allows to
specify encoding), or from the file system as java.io.File.
The other two interesting pieces of code are the ksession.insert method which injects the Account class into our
StatefulKnowledgeSession and the mehtod fireAllRules which is used to activate all rules defined.
When launched the Console should report the message fired from the rule

http://www.mastertheboss.com/jbossjbpm/drools/droolsexamplejbpm5?showall=1

3/5

5/4/2015

DroolsexamplejBPM5
Accountnamecannotbenull!
Of course verify that setting the name attribute, the message will not be displayed.

Now let's modify a bit our rule to make it more interesting:


{xtypo_code}rule "nameRequired"
when
$account : Account( name == null )
then
System.out.println( "Account name cannot be null!");
modify($account) {
setName("Unknown") )
};
end{/xtypo_code}
The modify block can contain many expressions (which must be separated by a comma (,)). This expression will actually
modify the account instance by calling the setName method. Now if you add a System.out of your account, just after firing
your rules, you will see that the rule was able to modify the model class:
1
2
3

Accounta=newAccount();
ksession.fireAllRules();
System.out.println(a.getName());

UsingGlobalvariablesinyourrules
Global variables are variables assigned to a session. They can be used for various reasons:
You can use tham as constants in your session
You can use them as output of your rule (think about a reportinga rule could write some message to a global report
variable)
You can use it as entry points for some services such as logging, which are used within rules

Now let's create our global object named RiskyAccounts which is a vector containing all accounts which have money less
than zero:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

packagecom.sample;

importjava.util.ArrayList;

publicclassRiskyAccounts{
privateArrayListaccounts=newArrayList();

publicvoidadd(Accountacc){
accounts.add(acc);
}
publicvoidlistRiskyAccounts(){
for(Accountacc:accounts)
System.out.println(acc);
}
}

Now we need to import it as global into our rule:


package samplerule
import com.sample.Account;
import com.sample.RiskyAccounts;
global RiskyAccounts risky;
rule "enoughMoney"
when
$account : Account( money < 0 )
then
System.out.println( "Not enough money on the account!");
risky.add($account);

http://www.mastertheboss.com/jbossjbpm/drools/droolsexamplejbpm5?showall=1

4/5

5/4/2015

DroolsexamplejBPM5
end
This rule simply adds the rule into the vector if money < 0
Next set the global variable into the rule session :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

publicstaticfinalvoidmain(String[]args)throwsException{
//loaduptheknowledgebase
KnowledgeBasekbase=readKnowledgeBase();
StatefulKnowledgeSessionksession=kbase.newStatefulKnowledgeSession();
//startanewprocessinstance
RiskyAccountsrisky=newRiskyAccounts();
ksession.setGlobal("risky",risky);
ksession.startProcess("com.sample.bpmn.hello");

Accountacc=newAccount();
acc.setName("JohnCheater");
acc.setMoney(10);
ksession.insert(acc);

ksession.fireAllRules();

risky.listRiskyAccounts();
}

Now your process will use the RiskyAccounts to store all Accounts which have a negative value for money attribute. Pretty
simple, isn't it ?

CONTACT US
Want to write for us? You would like to advertise here?

FOLLOW US ON TWITTER
Follow us on Twitter! @mastertheboss

TOP

http://www.mastertheboss.com/jbossjbpm/drools/droolsexamplejbpm5?showall=1

5/5

Anda mungkin juga menyukai