Tải bản đầy đủ (.pdf) (482 trang)

Manning JESS in action java rule based systems jul 2003 ISBN 1930110898 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.02 MB, 482 trang )

EXPERT SYSTEMS/JAVA

FREEBIES

JESS IN ACTION

Rule-Based
Systems in Java

Friedman-Hill

Rule-Based Systems in Java

• Binary version of Jess*
• Complete examples on the web
*For non-commercial use

Ernest Friedman-Hill
magine a different way to program in which you specify rules
and facts instead of the usual linear set of instructions. That’s the
idea behind rule-based programming. A rule engine automatically decides how to apply the rules to your facts and hands you
the result. This approach is ideal for expressing business rules and
is increasingly used in enterprise computing.

I

Jess in Action first introduces rule programming concepts and
teaches you the Jess language. Armed with this knowledge, you
then progress through a series of fully-developed applications
chosen to expose you to practical rule-based development. The
book shows you how you can add power and intelligence to your


Java software.
What’s Inside
■ Introduction to rule-based thinking
■ Jess language tutorial
■ Complete examples of ...
◆ Tax forms advisor
◆ Diagnostic assistant
◆ Fuzzy logic controller
◆ Web agent
◆ J2EE apps

—Ted Neward, Author
Server-Based Java Programming

“... the Jess book. A nice balance
between an introduction and a
reference ....”
—John D. Mitchell, Coauthor
Making Sense of Java

“Friedman-Hill writes clearly.
The topic is complicated, and he
does an excellent job explaining it
... I recommend this book.”
—Roedy Green, Author
The Java Glossary

“... intuitive and clever examples
that show the reader how to
build intelligent Java applications

with Jess.”
—Robert B. Trelease, Ph.D.
UCLA Brain Research Institute

IN ACTION
Ernest Friedman-Hill

www.manning.com/friedman-hill
AUTHOR




Dr. Friedman-Hill is the developer of Jess. A Principal Member of
the Technical Staff at Sandia National Laboratories, he lives in
Gaithersburg, MD.

JESS IN ACTION

Jess is a popular rule engine written in Java. It’s supported by
Sandia Labs and has an active online community. If you have a
problem that can be solved with rules, Jess in Action will show you
how. (If you are not sure, read chapter 2.) Written by the creator
of Jess, this book is an accessible and practical guide to rule-based
system development in Java.

“... clear, crisp, well-focused
... the organization is
smooth, well-thought-out,
... this book rocks.”


ONLINE

Author responds to reader questions
Ebook edition available

,!7IB9D0-bbaijc!:p;O;T;t;p
MANNING

$49.95 US/$74.95 Canada

ISBN 1-930110-89-8

MANNING

MANNING


Jess in Action



Jess in Action
Rule-Based Systems in Java
ERNEST FRIEDMAN-HILL

MANNING
Greenwich
(74° w. long.)



For online information and ordering of this and other Manning books, go to
www.manning.com. The publisher offers discounts on this book when ordered in
quantity. For more information, please contact:
Special Sales Department
Manning Publications Co.
209 Bruce Park Avenue
Greenwich, CT 06830

Fax: (203) 661-9018
email:

©2003 by Manning Publications Co. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
in any form or by means electronic, mechanical, photocopying, or otherwise, without
prior written permission of the publisher.

Many of the designations used by manufacturers and sellers to distinguish their products
are claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial
caps or all caps.

Recognizing the importance of preserving what has been written, it is Manning’s policy
to have the books they publish printed on acid-free paper, and we exert our best efforts
to that end.

Manning Publications Co.
Copyeditor: Tiffany Taylor
209 Bruce Park Avenue

Typesetter: Syd Brown
Greenwich, CT 06830
Cover designer: Leslie Haimes

ISBN 1-930110-89-8
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – VHG – 06 05 04 03


To my family



brief contents
PART 1

INTRODUCING RULE-BASED SYSTEMS ............... 1
1



Rules to the rescue 3

2



What are rule-based systems?

13


PART 2 JESS: A RULE-BASED
PROGRAMMING ENVIRONMENT ....................... 29
3



Introducing Jess

4



Getting started with the Jess language

5



Scripting Java with Jess

6



Representing facts in Jess

7




Writing rules in Jess

8



Under the hood: how Jess works

vii

31
61
74

95
133

41


viii

BRIEF CONTENTS

PART 3 CREATING YOUR FIRST RULE-BASED
APPLICATION: THE TAX FORMS ADVISOR ... 147

PART 4


PART 5

PART 6

PART 7

9



10



11



Collecting the knowledge 149
Designing the application 161
Writing the application 172

WRITING A DIAGNOSTIC APPLICATION:
THE PC REPAIR ASSISTANT ........................... 185
12



13




Writing the PC Repair Assistant 187
Adding a graphical interface 203

REASONING ABOUT REALITY:
THE HVAC CONTROLLER ............................. 219
14



15



16



The reality connection 221
Extending the Jess language 237
Writing the rules 255

TEKMART.COM: RULE-BASED APPLICATIONS
FOR THE WEB ................................................. 285
17



18




19



Jess on the Web 287
Embedding Jess in Java applications 306
Deploying web-based applications 323

ENTERPRISE SYSTEMS .................................... 355
20



21



A



B



C.




Jess, XML, and the enterprise 357
Jess in the J2EE environment 375
Jess functions 389
Abridged Java API for Jess 415
An automated testing framework

427


contents
preface xxi
acknowledgments xxiii
about this book xxvi
author online xxix
about the title xxx
about the cover illustration

PART 1

1

xxxi

INTRODUCING RULE-BASED SYSTEMS .............. 1
Rules to the rescue
1.1

3


Math class melee

4

Beyond logic puzzles

1.2

8

Some real-world examples 9
Mail filtering 9 Product configuration
Implementing business rules 11


1.3

2

Summary

12

What are rule-based systems?
2.1

10

13


The cooking/driving robot 14
Declarative programming: a different approach

2.2

Rules and rule engines
Expert systems

18
ix

17

15


x

CONTENTS

2.3

Architecture of a rule-based system 19
The inference engine 20 The rule base 21
The working memory 21 The pattern matcher
The agenda 22 The execution engine 23





22



2.4

Developing rule-based systems

23

Knowledge engineering 23 Structuring data 24
Testing 24 Interface building 25
Writing the rules 25 Iterative development 26






PART 2

2.5

Rule engine standards

2.6

Summary


26

27

JESS: A RULE-BASED
PROGRAMMING ENVIRONMENT

3

Introducing Jess
3.1

...................... 29

31

The Jess rule engine 32
Obtaining Jess 33 Installing Jess 33
Running Jess 34 “Hello, World” 34




3.2

Jess applications 36
Command line, GUI, or embedded?
Jess performance 38

3.3


4

Summary

37

39

Getting started with the Jess language
4.1

41

The basics 42
Whitespace 42 Symbols 42
The jess.Value class 43 Numbers
Strings 44 Comments 44




43



4.2

Adding some structure 45
Lists 45 Calling functions 46

Variables 47 More about lists 49




4.3

Control flow

50

foreach 51 while 52 if/then/else 52
progn 53 apply 54 eval and build 54






4.4



Defining functions with deffunction
Late binding

57

55



CONTENTS

4.5

Fine-tuning a function’s behavior
Take my advice, please

4.6

5

Summary

58

60

60

Scripting Java with Jess 61
5.1

Creating Java objects 62

5.2

Calling Java methods

64


Nesting function calls, and a shortcut 65
Calling static methods 66
Calling set and get methods 66
Working with arrays 67
How Jess chooses among overloaded methods

6

5.3

Accessing Java member data

5.4

Working with exceptions

5.5

Summary

69

70

73

Representing facts in Jess
6.1


68

74

Jess’s working memory

75

Manipulating the working memory

6.2

Just the facts, ma’am

6.3

Unordered facts

76

81

82

The deftemplate construct 82 Default slot values 83
Multislots 84 Changing slot values with modify 85
Copying facts with duplicate 85





6.4

Ordered facts

6.5

Shadow facts 87

86

Jess and JavaBeans 88 JavaBeans have “slots” 88
An example JavaBean 89 Creating a deftemplate for
DimmerSwitch 90 Putting a DimmerSwitch into working
memory 90 Static vs. dynamic shadow facts 91
Adding PropertyChangeListener support to DimmerSwitch 92
Shadow facts and working memory functions 94








6.6

Summary

94


xi


xii

CONTENTS

7

Writing rules in Jess
7.1

95

Forward-chaining rules 96
Patterns and shadow facts

7.2

100

Constraining slot data

100

Literal constraints 101 Variables as constraints 102
Connective constraints 104 Constraining matches with
predicate functions 105 Return value constraints 106
Pattern bindings 107







7.3

Qualifying patterns with conditional elements 108
The and conditional element 108 The or conditional
element 109 The not conditional element 111
The test conditional element 113
The logical conditional element 114




7.4

Backward-chaining rules

7.5

Managing the agenda 120

116

Conflict resolution 121
Changing rule priority with salience


7.6

121

Partitioning the rule base with defmodule 123
Defining constructs in modules 123
Modules, scope, and name resolution 124
Module focus and execution control 126

7.7

Searching working memory with defquery

128

The variable declaration 130 Query trigger facts
The count-query-results function 131
Backward chaining and queries 131


7.8

8

Summary

131

Under the hood: how Jess works 133
8.1


Review of the problem 134

8.2

An inefficient solution 135

8.3

The Rete algorithm 136
How Rete works

136



Handling retract

139

8.4

Easy optimizations for Rete 139

8.5

Performance of the Rete algorithm 141
Node index hash value

141


130


CONTENTS

8.6

More complexity and initial-fact

142

Implementing the not conditional element
Implementing the test conditional element
Implementing backward chaining 143

8.7

Exploring the Rete network in Jess

142
143

143

The (watch compilations) command 143
The view function 144 The matches function


8.8


PART 3

9

Summary

146

146

CREATING YOUR FIRST RULE-BASED
APPLICATION: THE TAX FORMS ADVISOR ... 147
Collecting the knowledge

149

9.1

The Tax Forms Advisor

9.2

Introduction to knowledge engineering 150
Where do you start? 151
Desk research 156

9.3

9.4


150
Interviews



Summary



Reviewing the forms

160

Designing the application
10.1

Organizing the data 162

10.2

Filling in details
Default slot values

161

163
163

10.3


More templates

10.4

Templates you don’t need

10.5

Organizing the rules

10.6

Building the infrastructure

164
165

166

Simple text-based I/O 167
Fetching the question text 168

10.7

153

Collecting knowledge about tax forms 157
An interview 157
Next steps 160


10

xiii

Summary 170

166

159


xiv

CONTENTS

11

Writing the application
11.1

172

Welcoming the user 173
Testing the startup module

11.2

173


Asking the user questions

174

Income and dependents 175
Dealing with special circumstances 176
Testing the interview module 177

11.3

Recommending forms 177

11.4

Explaining the results

181

Testing the report module

PART 4

12

182

11.5

Finishing touches


11.6

Testing the full application

11.7

Summary 184

182
183

WRITING A DIAGNOSTIC APPLICATION:
THE PC REPAIR ASSISTANT .......................... 185
Writing the PC Repair Assistant
12.1

Using flowcharts in knowledge engineering 188
From flowcharts to rules

12.2

187

189

The problem domain 190
Writing the first rules

191


12.3

Asking questions with backward chaining 193

12.4

Checking the answers

194

Modifying the ask module

12.5

The rest of the rules

195

197

Rules about sound 197 Degrading gracefully 198
To boot, or not to boot 199 RAM problems 199
Questioning authority 200




12.6

Testing


12.7

Summary 202

201


CONTENTS

13

Adding a graphical interface
13.1

Getting started

13.2

Displaying a window 205

13.3

Displaying questions 206

13.4

Getting answers

203


204

207

The main thread vs. the event thread

PART 5

14

13.5

Better input components

13.6

Finishing touches

13.7

Testing the interface

13.8

Summary 216

209

213


214
215

REASONING ABOUT REALITY:
THE HVAC CONTROLLER ........................... 219
The reality connection

221

14.1

The system

14.2

Defining the hardware interface

223
224

Native methods 224 Writing a simulator
Simulating getTemperature 227
Adding a graphical interface 229


14.3

225


Writing the JavaBeans 229
Rules about Thermometers 232
Writing the other Beans 233

15

xv

14.4

JavaBeans and serialization

14.5

Summary 235

235

Extending the Jess language
15.1

237

The Userfunction interface

238

The getName method 239 The call method
Loading a Userfunction into Jess 239



15.2

Handling arguments

239

240

How many arguments? 240 Using arguments
Resolving variable arguments 242
Resolving function call arguments 243


241


xvi

CONTENTS

15.3

Returning a value 245
Constructing Value objects

15.4

245


Beyond simple examples

246

Holding state 246 Multiple personalities
Userfunctions and serialization 247
Grouping functions with Userpackage 247


15.5

The HVAC functions

246

248

Creating a simulator 248 Counting devices
Matching heat pumps and floors 250
Operating the hardware 251
Implementing a Userpackage 253


16

15.6

Testing 253

15.7


Summary 254

Writing the rules
16.1

249

255

The control algorithm

256

Knowledge engineering with truth tables 256
How heat pumps work 257 Using guard lines
Saving energy 258


16.2

Setting up

16.3

Controlling the heat pumps

258

Enough is enough


16.4

257

260

Controlling the vents
The vent rules



259

The moment of truth

261

262

262

16.5

Testing the whole system

16.6

Controlling with fuzzy rules 264


263

Fuzzy logic, briefly 265 The Fuzzy HVAC Controller
Exploring the fuzzy controller 282


16.7

What’s next? 282

16.8

Summary 283

269


CONTENTS

PART 6

17

TEKMART.COM: RULE-BASED APPLICATIONS
FOR THE WEB .............................................. 285
Jess on the Web
17.1

287


Java architectures for the Web
Fat-client applications

288



288

Thin-client applications

17.2

A Jess application for the Web

17.3

Knowledge engineering 292

17.4

Designing data structures 293

17.5

Writing the rules

295







17.6

Refining the recommendations

17.7

Some useful queries

17.8

Cleaning up

17.9

Summary 304

300

301

Maintaining the order number

302

303


Embedding Jess in Java applications 306
18.1

Getting started with the Jess library

307

The executeCommand method 308
Exchanging Java objects 308
Beyond executeCommand 310

18.2

Working with Fact objects in Java
Multislots 313 Ordered facts
Removing facts 314


Working with JavaBeans

18.4

Calling Jess functions from Java

18.5

Working with JessException

18.6


317

314

Summary 321

315

316

Rolling your own

Input and output 319
Using custom routers

18.7



311

313

18.3

Nested exceptions

290

292


About testing 295 The recommend-requirements rule
Recommending videos and DVDs 297 Conspicuous
consumption 298 More media rules 299

18

xvii

320

318

296


xviii

CONTENTS

19

Deploying web-based applications
19.1

The Java Servlet API

19.2

J2EE and the Tomcat engine


325

Deploying the Hello servlet

19.3

Your first Jess servlet

326

326

329

Deploying the Jess servlet

330



Cleaning up the URL

19.4

Application architecture: take one

19.5

Starting the Catalog servlet 332

JavaServer Pages

323

332

331

Forwarding to a JSP



19.6

Application architecture, take two

19.7

The login screen

19.8

The Catalog servlet 337

331

333

335


335

Initializing Jess 337 Getting the login name 338
Starting a user session 339 Querying the product list
Invoking the JSP 340 The catalog JSP 341




340



19.9
19.10

Testing

343

The Recommend servlet 343
Getting started 344 Creating the order
Getting the recommendations 345
Forwarding to JSPs 346


PART 7

20


19.11

The recommend JSP

19.12

The Purchase servlet 348

19.13

Persistence

19.14

Deploying the application

19.15

What’s next? 352

19.16

Summary

344

346

350
351


353

ENTERPRISE SYSTEMS ................................... 355
Jess, XML, and the enterprise
20.1

Enterprise applications
What is the J2EE?

359

357

358


What does that stand for?

359


CONTENTS

20.2

Rules and XML

360


Interoperability 361 Editing and other processing
Storage and retrieval 362


20.3

XML-based rule representations

363

RuleML 363 DAML 364
Homegrown representations 365
Strategies for representing rules in XML


20.4

Representing Jess rules in XML
An example rule 368
into Jess rules 369

21

20.5

Rule editors

20.6

Summary 374




367

Transforming the XML rules

372

Jess in the J2EE environment
21.1

365

375

A quick tour of EJB concepts

376

Kinds of EJBs 376 n EJB restrictions 377
Do you need to use EJBs? 377
Accessing external resources from EJBs 378

21.2

An RMI-based rule server

379


The remote interfaces 379 Implementing the
interfaces 380 Implementing a main method 382
Generating the stubs 382 A sample client 382
Final polishing 383






21.3

JSR 94: the javax.rules API

383

Working with javax.rules 384
The reference implementation 386

21.4

A
B
C

Summary 388

Jess functions

389


Abridged Java API for Jess

415

An automated testing framework
index

433

427

362

xix



preface
In 1994, I was working in the Scientific Computing department at Sandia National
Laboratories in Livermore, California. We had an impressive (for the time) array
of heterogeneous computing equipment: workstations from Silicon Graphics and
Sun Microsystems, Intel PCs running Linux, Macintoshes galore. I was writing
software agents that managed dynamically distributed computations across this
network. Agents were running on each machine, and they used a sort of “post and
bid” method to decide which machines would run which piece of a computation,
based on machine capabilities and load balancing. The agents were fairly intelligent in their decision-making capabilities, and the plans they developed were
sometimes surprising. Their “brains” were rule engines—software systems that used
rules to derive conclusions from premises.
That project led to others, and soon I developed an interest in mobile agents—

software entities that can travel from node to node in a computer network, maintaining their state as they go. Thus was born the idea for a rule engine whose state
could be packaged up, sent across a wire, and reconstituted. The newly released
Java language seemed to be a perfect vehicle for this rule engine—and such was
the origin of Jess™, the rule engine for the Java Platform.1
Jess is a general-purpose rule engine, developed at Sandia National Laboratories. Written in the Java programming language, Jess offers easy integration with
1

Jess is a registered trademark of the Sandia Corporation.

xxi


xxii

PREFACE

other Java-based software. Jess is free for academic and government use, and it
can be licensed for commercial use. You can download a fully functional Home
Edition of Jess free of charge if you own a copy of this book (see chapter 3 for
download instructions). You can use the Jess Home Edition for noncommercial
purposes.
Jess has evolved quite a bit since its original introduction in 1997, largely in
response to feedback from a global user community. I’ve enjoyed working on Jess
the whole time, and look forward to its continuing evolution in the future.


acknowledgments
Writing a book is a huge project. This is my second book, and somehow I thought
it would be easier this time around. It wasn’t. The original four-month estimate to
write the manuscript has stretched out into much more than a year. I’m very

happy with the results, though. Writing a book about a subject so near and dear as
Jess is to me is a dodgy business: I think I’ve steered clear of the minefields of selfindulgence and created something that will be useful to everyone interested in
rule-based software.
Writing a book is such a huge project, in any event, that no one does it alone—
least of all me. I’ve had help from many kind, generous, and talented people during the whole time this book was being developed.
One standout has been Bob Orchard of Canada’s National Research Council.
Bob is the author of the FuzzyJ toolkit and the FuzzyJess extension that adds fuzzy
logic to Jess. He’s been an active member of the Jess community for years. He generously contributed the essay in chapter 16 showing how to apply the principles of
fuzzy logic to the HVAC Controller example. He also served as both a technical
reviewer and a technical proofreader for this book and provided an exhaustive list
of my (embarrassingly many) typos in the first draft of the manuscript. Thanks,
Bob, for everything!
Next I must mention the denizens of the Jess mailing list, a friendly community
of smart and generous people who have come together over the years that Jess has
existed. The following people have helped find bugs, helped develop new features,

xxiii


xxiv

ACKNOWLEDGMENTS

or contributed their own projects to the Jess community: Abel Martinez, Al Davis,
Alan Moore, Alex Jacobson, Alex Karasulu, Andreas Rasmusson, Andrew Marshall,
Ashraf Afifi, Benjamin Good, Blaine Bell, Bob Orchard, Bob Trelease, Bruce Douglas, Chad Loder, Charles May, Cheruku Srini, Dan Larner, Dave Barnett, Dave
Carlson, Dave Kirby, David Bruce, David Li, David Young, Drew van Duren, Duane
Steward, Ed Katz, Emmanuel Pierre, Eric Eslinger, Fang Liu, George Rudolph,
Glen Tarbox, Glenn Williams, Henrik Eriksson, Ian de Beer, J.P. van Werkhoven,
Jacek Gwizdka, Jack Fitch, Jack Kerkhof, James Gallogly, James Owen, Jason Smith,

Javier Torres, John Callahan, John Collins, Joszef Toth, Juraj Frivolt, Karl Mueller,
Ken Bertapelle, Kenny Macleod, Lakshmi Vempati, Lars Rasmusson, Laurence
Leff, Mariusz Nowostawski, Matt Bishop, Matthew Johnson, Michael Coen, Michael
Friedrich, Michael Futtersack, Michal Fadljevic, Michelle Dunn, Mikael Rundqvist,
Mike Finnegan, Mike Isenberg, Mike Lucero, Miroslav Madecki, Nancy Flaherty,
Ning Zhong, Norman Ghyra, Oliver Hoffman, Osvaldo Pinali Doederlein, Pau
Ortega, Peter Hanson, Peter Klotz, Ralph Grove, Richard Long, Rob Jefson, Robert
Gaimari, Russ Milliken, S. S. Ozsariyildiz, Sander Faas, Scott Kaplan, Scott Trackman, Sebastian Varges, Seung Lee, Sidney Bailin, Simon Blackwell, Simon Hamilton, Steve Bucuvalas, Thomas Barnekow, Thomas Gentsch, Travis Nelson, William
E. Wheeler, Win Carus, and Yang Xiao. I’m sure I’ve forgotten someone important;
please forgive the oversight.
The staff at Manning Publications, both past and present, are talented people
and real professionals. I thank Marjan Bace for his guidance and eye for the big
picture; Lianna Wlasiuk for her useful and practical advice in the first stages of
writing; Ann Navarro for her expertise in editing; Tiffany Taylor for the tremendous skill and effort she applied to meticulously copy-editing and formatting my
ill-formed manuscript; Syd Brown, who produced the beautiful example of the
typographer’s art you see before you; Maggie Mitchell, for proofreading; Mary
Piergies, for overseeing the production of this book; Ted Kennedy for gathering a
team of excellent reviewers and organizing the results; Dan Barthel, who got me
started on this book in the first place; and, undoubtedly, many others who worked
behind the scenes.
Quite a few technical reviewers and friends read the manuscript and provided
detailed and useful comments. This book is vastly improved by their input; any
remaining problems are, of course, my fault. I thank Andrew Grothe, Bob Trelease, David Young, Jeff Wang, John Crabtree, John Mitchell, Mark Watson,
Michael J. Smith, Roedy Green, Said Tabet, Ted Neward, and Daniel Selman (and
of course Bob Orchard) for reading and commenting on the manuscript.


×