Drools JBoss Rules 5.0 Developer's Guide - Bali Michal - E-Book

Drools JBoss Rules 5.0 Developer's Guide E-Book

Bali Michal

0,0
26,01 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In Detail

Business rules can help your business by providing a level of agility and flexibility. As a developer, you will be largely responsible for implementing these business rules effectively, but implementing them systematically can often be difficult due to their complexity. Drools, or JBoss Rules, makes the process of implementing these rules quicker and handles the complexity, making your life a lot easier!

This book guides you through all of the features of Drools, such as dynamic rules, the event model, and Rete implementation with high performance indexing. It will help you to set up the JBoss Rules platform and start creating your own business. It's easy to start developing with Drools if you follow its real-world examples that are intended to make your life easier.

Starting with an introduction to the basic syntax that is essential for writing rules, the book will guide you through validation and human-readable rules that define, maintain, and support your business agility. As a developer, you will be expected to represent policies, procedures and. constraints regarding how an enterprise conducts its business; this book makes it easier by showing you it can be done.

A real-life example of a banking domain allows you to see how the internal workings of the rules engine operate. A loan approval process example shows the use of the Drools Flow module. Parts of a banking fraud detection system are implemented with Drools Fusion module, which is the Complex Event Processing part of Drools. This in turn, will help developers to work on preventing fraudulent users from accessing systems in an illegal way.

Finally, more technical details are shown on the inner workings of Drools, the implementation of the ReteOO algorithm, indexing, node sharing, and partitioning.

A developer's guide to the powerful Java business rules platform.

Approach

This is a problem-solution guide that starts with an introduction to a problem and continues with a discussion of the possible solution. The book covers best practices when working with Drools. The examples and their solutions are accompanied by plenty of code listings and figures providing a better view of the problem.

Who this book is for

The book is for Java developers who want to create rules-based business logic using the Drools platform. Basic knowledge of Java is essential.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 395

Veröffentlichungsjahr: 2009

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Drools JBoss Rules 5.0 Developer's Guide
Credits
Foreword
Open Source Decision Management
About the Author
About the Reviewers
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code for the book
Errata
Piracy
Questions
1. Introduction
Problems with traditional approaches
The solution
Advantages
Disadvantages
When not to use a rule engine
Drools
Alternatives to Drools
Summary
2. Basic Rules
Rule basics
Executing rules
Rule syntax
Rule concepts
Variables in rules
Types
Comments
Package
Imports
Global variables
Functions
Dialect
mvel
Rule condition
And
Or
Not
Exists
Eval
Return value restriction
Inline eval
Nested accessors
This
Working with collections
(Not) contains
(Not) memberOf
From
Rule consequence
Rule attributes
salience (priority)
No-loop
Dialect
Summary
3. Validation
Banking domain model
Problem definition
Analysis
Design
Validation package
Object required type rules
Testing
Minimal account balance rule
Student account rule
Unique account number rule
Implementation
Validation service
Summary
4. Data Transformation
Process overview
Getting the data
Loading facts into the knowledge session
Writing transformation rules
Testing
Address normalization
Testing the findAddress rule
Unknown country
Currency conversion
One account allowed
Transformation results
Implementation of the data loading
Database setup
Project setup
iBatis configuration
Running iBatis
Alternative data loading
Summary
5. Human-readable Rules
Domain Specific Language
DSL as an interface
DSL for validation rules
File formats
DSL file format
DRL file format
DSLR file format
DSL for multiple constraints in a condition
Named capture groups
DSL for data transformation rules
Decision tables
Advantages of a decision table
Disadvantages of a decision table
Calculating the interest rate
Project setup
Testing
Comma Separated values
Rule Templates
Drools Flow
Drools Agenda
Methods for managing rule execution order
Ruleflow
Start
End
Action
RuleFlowGroup
Split
Join
Example
Rules
KnowledgeBase setup
Tests
Summary
6. Stateful Session
Introduction to stateful session
Validation using stateful session
Design overview
Stateful validation service
Integration testing
Logical assertions
Keeping the validation report up-to-date
Collect conditional element
Collect
Serialization
Knowledge session re-creation
Testing
Session serialization
Full session serialization
Summary
7. Complex Event Processing
CEP and ESP
Drools Fusion
Fraud detection
Problem description
Monitoring:
Design and modeling
Fraud detection rules
Notification
Test configuration setup
Testing the notification rule
Monitoring—averageBalanceQuery
Testing the averageBalanceQuery
Two large withdrawals
Testing the twoLargeWithdrawals rule
Sequence of increasing withdrawals
Average balance test
Testing the sequenceOfIncreasingWithdrawals rule
High activity
Testing the highActivity rule
Summary
8. Drools Flow
Loan approval service
Model
Loan approval ruleflow
Invalid loan application form
Email work item
Fault node
Test setup
Testing the 'otherwise' branch of 'Validated?' node
The size of the loan
Test for a small loan
Rating Calculation
Subflow
Subflow diagram
Rating calculation subflow test
Decisions on rating
Testing the 'Rating?' node
Transfer Funds work item
Work item definition
Work item registration
Work item handler
Work item handler registration
Testing the transfer work item
Human task
Test for the human task
Final Approval
Test for the 'Approve Event' node
Banking service
Disadvantages of a ruleflow
Summary
9. Sample Application
Users
Architecture
Technologies used
Additional Drools projects used
Libraries used
Business logic
Design
Configuration
JPA annotations for domain objects
JPA configuration
Spring Framework configuration
Web application setup
Tag library
Tomcat setup
Deployment
Repositories
Validation
Services
Transactions
Presentation layer
Localized messages
Customer save form controller
Complex Event Processing service
Loan approval
Loan request form
Process persistence
Task list
Working on a task
Loan approval event
Summary
10. Testing
How to write unit tests for rules
Rule integration testing
Rule acceptance testing
Creating a test scenario
Running a test scenario
Running all test scenarios
Static analysis of rules
Troubleshooting techniques
Event listeners
Debugging
Ruleflow
Source of generated classes
mvel tricks
Summary
11. Integration
Dynamic KnowledgeBase loading
KnowledgeAgent
External artifact building
Building with Ant
Drools execution server
Interest rate calculation example
The server
The client
Spring Framework integration
KnowledgeBaseFactoryBean
Standards
JSR94 Java Rule Engine API
Summary
12. Performance
Rete algorithm
Node types
Rete node
EntryPointNode
ObjectTypeNode
AlphaNode
LeftInputAdapterNode
TerminalNode
Example 1—inserting a fact
BetaNode
Example—inserting a fact
More complex example
EvalNode and FromNode
Retracting or modifying a fact
Initial fact
Node sharing
Example
Node indexing
AlphaNode indexing
Computation complexity
BetaNode indexing
Example
KnowledgeBase partitioning
Parallel execution
Summary
A. Development Environment Setup
Environment setup
Dependencies and their licenses
B. Custom Operator
Summary
C. Dependencies of Sample Application
Index

Drools JBoss Rules 5.0 Developer's Guide

Michal Bali

Drools JBoss Rules 5.0 Developer's Guide

Copyright © 2009 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: July 2009

Production Reference: 1060709

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847195-64-7

www.packtpub.com

Cover Image by Vinayak Chittar (<[email protected]>)

Credits

Author

Michal Bali

Reviewers

James Taylor

Sammy Larbi

Acquisition Editor

Sarah Cullington

Development Editor

Siddharth Mangarole

Technical Editors

Aanchal Kumar

Conrad Sardinha

Indexer

Rekha Nair

Editorial Team Leader

Gagandeep Singh

Project Team Leader

Priya Mukherji

Project Coordinator

Zainab Bagasrawala

Proofreader

Claire Lane

Production Coordinator

Shantanu Zagade

Cover Work

Shantanu Zagade

Foreword

Open Source Decision Management

Companies of every size are realizing that smart, simple, agile processes require that operational decisions should be managed, automated, and improved. These high volume transactional decisions must be made to keep data flowing through processes, to empower customers to self-serve, to make systems act more intelligently. As Neil Raden and I discussed in Smart (Enough) Systems, these decisions commonly have distinct characteristics. These decisions are high volume, low latency, and necessary for both straight through processing and unattended operation so they must be automated. Yet they must also change in response to external variability, demonstrate compliance, manage risk, and be personalized so traditional approaches to automation are problematic. Coding decisions in Java makes it hard to show those decisions to a regulator to prove compliance and hard to change the decision making approach quickly and cheaply. It makes it hard for business users to truly collaborate on how these decisions should be made, limiting the ability to bring risk management and personalization to these decisions.

Fortunately, there exists a technology and an approach to deal with these challenges. Instead of using traditional approaches companies attacking the decisions as a separate problem and managing those decisions explicitly. Decision management externalizes these decisions as decision services so they can reused and systematically improved. Decision management replaces traditional procedural code with business rules—declarative, atomic, manageable fragments of business logic. Business rules allow business users to participate in writing business logic.

With Drools 5, JBoss and the open source community have delivered a true business rules management system for the first time. Using Drools, organizations can take control of the logic that drives their operational decisions. They can build simpler, smarter, and more agile business processes and systems.

Michal introduces business rules and JBoss Drools to programmers in this book, walking them through all the major features of the product. Extensive code extracts and worked examples illustrate all the major, and many of the minor, features in the new release. Whether you are new to Drools or used to a previous version, Michal's book will help you navigate the new release. With Drools 5 you can take control of the logic in your systems and manage your decisions for better business results and greater agility, and this book will show you how.

It's time to change the way you build system, time to manage operational decisions, time to put business rules to work.

James Taylor

CEO, Decision Management Solutions

Author, with Neil Raden, of Smart (Enough) Systems (Prentice Hall, 2007)

blog: jtonedm.com, twitter: jamet123

About the Author

Michal Bali is a senior software developer at DeCare Systems, Ireland. He has four years experience working with Drools and has extensive knowledge of Java, JEE. Michal designed and implemented several systems for a major dental insurance company. Michal is an active member of the Drools community and can be contacted at <[email protected]>.

I thank Drools lead Mark Proctor and his team that consists of Edson Tirelli, Michael Neale, Kris Verlaenen, Toni Rikkola, and other contributors for giving me something to write about. They were of great help while I was writing the book. Edson and Mark reviewed the book and helped me to correct various inaccuracies.

I'd like to thank all reviewers and the whole editorial team for their patience and help while I was writing this book. In particular, Sarah Cullington, Siddharth Mangarole, Aanchal Kumar, Conrad Sardinha, James Taylor, Sammy Larbi, Zainab Bagasrawala, Shilpa Dube, Lata Basantani, and other anonymous reviewers.

I thank James Taylor for writing the foreword and reviewing the book. I am honored that he chose to participate in this project.

Finally, I thank my fiancée Michala for supporting me and putting up with me while I wrote.

About the Reviewers

James Taylor is CEO of Decision Management Solutions and one of the leading experts in decision management. James works with clients to develop effective technology solutions to improve business performance. He has over 20 years experience in developing software and is the foremost thinker and writer on decision management. James was previously a Vice President at Fair Isaac Corporation where he developed and refined the concept of enterprise decision management. The best known proponent of the approach, James is a passionate advocate of decision management.

James has experience in all aspects of the design, development, marketing, and use of advanced technologies including CASE tools, project planning, and methodology tools as well as platform development in PeopleSoft's R&D team and management consulting with Ernst and Young. He develops approaches, tools, and platforms that others can use to build more effective information systems.

James is the lead author of Smart (Enough) Systems: How to Deliver Competitive Advantage by Automating Hidden Decisions (Prentice Hall, 2007) and he has contributed chapters to The Decision Model (forthcoming), The Business Rules Revolution: Doing Business The Right Way, and Business Intelligence Implementation: Issues and Perspectives. James writes several blogs and his articles appear in industry magazines and on leading industry and technical web sites.

Sammy Larbi works as a programmer for desktop, web, console, and service applications using a diverse range of technologies, including Ruby, .NET, ColdFusion, Java, C/C++, and Perl. In addition to typical and atypical business domains, he also works in the field of bioinformatics and has a keen interest in artificial intelligence.

After many long years and sleepless nights since learning to program in his youth, he graduated with degrees in Computer Science and Political Science in 2004, and finished a master's degree in Computer Science in 2008.

Sam shares his thoughts about programming and software development online at his weblog, www.codeodor.com.

Preface

Business rules and processes can help your business by providing a level of agility and flexibility. As a developer, you will be largely responsible for implementing these business rules and processes effectively, but implementing them systematically can often be difficult due to their complexity. Drools, or JBoss Rules, makes the process of implementing these rules and processes quicker and handles the complexity, making your life a lot easier!

This book guides you through various features of Drools, such as rules, ruleflows, decision tables, complex event processing, Drools Rete implementation with various optimizations, and others. It will help you to set up the Drools platform and start creating your own business. It's easy to start developing with Drools if you follow our real-world examples that are intended to make your life easier.

Starting with an introduction to the basic syntax that is essential for writing rules, the book will guide you through validation and human-readable rules that define, maintain, and support your business agility. As a developer, you will be expected to represent policies, procedures, and constraints regarding how an enterprise conducts its business; this book makes it easier by showing you the ways in which it can be done.

A real-life example of a banking domain allows you to see how the internal workings of the rules engine operate. A loan approval process example shows the use of the Drools Flow module. Parts of a banking fraud detection system are implemented with Drools Fusion module, which is the Complex Event Processing part of Drools. This in turn, will help developers to work on preventing fraudulent users from accessing systems in an illegal way.

Finally, more technical details are shown on the inner workings of Drools, the implementation of the ReteOO algorithm, indexing, node sharing, and partitioning.

What this book covers

Chapter 1: This chapter introduces the reader to the domain of business rules and business processes. It talks about why the standard solutions fail at implementing complex business logic. It shows a possible solution in the form of a declarative programming model. The chapter talks about advantages and disadvantages of Drools. A brief history of Drools is also mentioned.

Chapter 2: This chapter shows us the basics of working with the Drools rule engine—Drools Expert. It starts with a simple example that is explained step-by-step. It begins with the development environment setup, writing a simple rule, and then executing it. The chapter goes through some necessary keywords and concepts that are needed for more complex examples.

Chapter 3: This chapter introduces the reader to a banking domain that will be the basis for examples later in this book. The chapter then goes through an implementation of a decision service for validating this banking domain. A reporting model is designed that holds reports generated by this service.

Chapter 4: This chapter shows how Drools can be used for carrying out complex data transformation tasks. It starts with writing some rules to load the data, continues with the implementation of various transformation rules, and finally puts together the results of this transformation. The chapter shows how we can work with a generic data structure such as a map in Drools.

Chapter 5: The focus of this chapter is on rules that are easy to read and change. Starting with domain specific languages, the chapter shows how to create a data transformation specific language. Next, it focuses on decision tables as another more user-friendly way of representing business rules. An interest rate calculation example is shown. Finally, the chapter introduces the reader to Drools Flow module as a way of managing the rule execution order.

Chapter 6: This chapter talks about executing the validation decision service in a stateful manner. The validation results are accumulated between service calls. This shows another way of interacting with a rule engine. Logical assertions are used to keep the report up-to-date. Various ways of serializing a stateful session are discussed.

Chapter 7: This chapter talks about Drools Fusion—another cornerstone of the Drools platform is about writing rules that react to various events. The power of Drools Fusion is shown through a banking fraud detection system. The chapter goes through various features such as events, type declarations, temporal operators, sliding windows, and others.

Chapter 8: This chapter goes into more detail about the workflow aspect of the Drools platform. It is showed through a loan approval service that demonstrates the use of various nodes in a flow. Among other things, the chapter talks about implementing a custom work item, human task, or a sub-flow.

Chapter 9: The purpose of this chapter is to show you how to integrate Drools in a real web application. We'll go through design and implementation of persistence, business logic, and presentation layers. All of the examples written so far will be integrated into this application.

Chapter 10: The focus of this chapter is to give you an idea about the various ways of testing your business logic. Starting with unit testing, integration testing through acceptance testing that will be shown with the help of the Business Rules Management Server—Guvnor, this chapter provides useful advice on various troubleshooting techniques.

Chapter 11: This chapter shows integration with the Spring Framework. It describes how we can make changes to rules and processes while the application runs. It shows how to use an external build tool such as Ant to compile rules and processes. It talks about the rule execution server that allows us to execute rules remotely. It briefly mentions support of various standards.

Chapter 12: This chapter goes under the hood of the Drools rule engine. By understanding how the technology works, you'll be able to write more efficient rules and processes. It talks about the ReteOO algorithm, node sharing, node indexing, and rule partitioning for parallel execution.

Appendix A: It lists various steps required to get you up and running with Drools.

Appendix B: It shows an implementation of a custom operator that can be used to simplify our rules.

Appendix C: It lists various dependencies used by the sample web application.

What you need for this book

In order to learn Drools and run the examples in this book, you'll need a computer with any Operating System (Windows, Mac, or Linux), Java Development Kit (JDK) version 1.5 or later, Drools binary distribution, some IDE—preferably Eclipse IDE for Java EE developers, Drools plugin for Eclipse, and some third-party libraries that will be specified per chapter. All of the mentioned software is freely available on the Internet under a business friendly license.

You can download some additional support material from http://code.google.com/p/droolsbook/.

Who this book is for

The book is for Java developers who want to create rules-based business logic using the Drools platform. Basic knowledge of Java is essential.

Note

Readers are requested to note that they should follow the text carefully. Some additions to the code are required in order to run the examples successfully.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "Drools keywords are rule, when, then, and end."

A block of code will be set as follows:

package droolsbook; rule "basic rule" when Account( balance < 100 ) // condition then System.out.println("Account balance is " + "less than 100"); // consequence end

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: "After it finishes execution, Action is executed, the flow continues to another ruleflow group called Group 2, and finally it finishes at an End node".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply drop an email to <[email protected]>, and mention the book title in the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code for the book

Visit http://www.packtpub.com/files/code/5647_Code.zip to directly download the example code.

The downloadable files contain instructions on how to use them.

Errata

Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to any list of existing errata. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or web site name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Drools

Drools is a Business Logic integration Platform (BLiP). It is written in Java. It is an open source project that is backed by JBoss and Red Hat, Inc. It is licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html). This book will focus on version 5.0 of this platform that was released in May 2009.

Work on Drools (the rule engine) began in 2001. From its beginning, Drools underwent many changes. Drools 1.0 started with a brute force linear search. It was then rewritten in version 2.0, which was based on the Rete algorithm. The Rete algorithm boosted Drools performance. Rules were written mainly in XML. The next version (3.0) introduced a new .drl format. This is a specific language specially crafted for writing rules. It proved to be a great success and it became the main format for writing rules. Version 4.0 of the rule engine had some major performance improvements together with the first release of a Business Rules Management System (BRMS). This formed the base for the next big release (5.0) where Drools became a Business Logic integration Platform. The platform consists of four main modules:

Drools Expert: The rule engine itself.Drools Fusion: Complex Event Processing (CEP) module. It will be covered in Chapter 7, Complex Event Processing.Drools Flow: Workflow—combines rules and processes together. It will be introduced at the end of Chapter 6, Stateful Session and then fully covered by Chapter 8, Drools Flow.Drools Guvnor: A Business Rules Management System (BRMS). It won't be covered in this book except for testing and rule analysis in Chapter 10, Testing.Drools Solver: This is an optional module. It's a search algorithm built on top of the Drools rule engine to solve planning problems (for example, creating timetables). It won't be covered in this book.

Another very important part of Drools is its Eclipse plugin. It greatly helps with writing and debugging rules and processes. It checks for syntax errors, offers auto completion, and has lots of other useful features.

Drools has a very active and friendly community. It is growing every year. You can get in touch with this community by visiting the Drools blog, wiki, or the mailing lists. For more information, please visit Drools web site at http://www.jboss.org/drools/.

Alternatives to Drools

For completeness, we'll also mention alternative rule engines/expert systems. These include commercial products such as ILOG (now IBM)—JRules, Fair Isaac—Blaze Advisor, Corticon's BRMS, Haley (now Oracle) Business Rules Engine, Pegasystems—PegaRules, Production Systems Technologies—OPSJ, Innovations Software. Some products for the .NET platform are: Microsoft BizTalk Server, InRule for Windows Workflow Foundation, ILOG, and Fair Isaac. Alternative open source products include CLIPS and products with dual licenses such as OpenRules or Jess.

Alternatively, you can build a rule engine yourself. It may be appropriate in some specific scenario, but most of the time you'll only be re-inventing the wheel. More importantly, your solution probably won't be as efficient as an existing mature product such as Drools.

Summary

We've learned why there is a need for a BLiP such as Drools, what problems it is trying to solve, and in what way it is trying to solve them. We've seen the advantages and disadvantages of this solution.

Drools provides a different computational model for business process and rule execution. It is a generic algorithm with generic optimizations to provide 'good enough' performance while giving us lots of benefits such as flexibility and declarative programming.

We know that this platform consists of multiple modules and in the following chapters we're going to look at them in more detail, starting with the core rule engine itself—Drools Expert.