Este contenido no está disponible en el idioma seleccionado.

Chapter 9. Building


9.1. Build Result Severity

You can change the default severity of a type of build result. This can be useful if, for example, a new rule with a duplicate name of an existing rule is added to a package. (In this case, the default behavior is to replace the old rule with the new rule and report it as an INFO.) In some deployments the user might want to prevent the rule update and report it as an error.

9.2. Setting the Default Build Result Severity

Procedure 9.1. Task

  1. To configure it using system properties or configuration files, insert the following properties:
    // sets the severity of rule updates
    drools.kbuilder.severity.duplicateRule = <INFO|WARNING|ERROR>
    // sets the severity of function updates
    drools.kbuilder.severity.duplicateFunction = <INFO|WARNING|ERROR>
    
    Copy to Clipboard Toggle word wrap
  2. To use the API to change the severities, use this code:
    KnowledgeBuilderConfiguration kbconf = ...
    
    // sets the severity of rule updates to error
    kbconf.setOption( KBuilderSeverityOption.get( "drools.kbuilder.severity.duplicateRule", ResultSeverity.ERROR ) ); 
    // sets the severity of function updates to error
    kbconf.setOption( KBuilderSeverityOption.get( "drools.kbuilder.severity.duplicateFunction", ResultSeverity.ERROR ) );
    
    Copy to Clipboard Toggle word wrap

9.3. KnowledgePackage

A Knowledge Package is a collection of Knowledge Definitions, such as rules and processes. It is created by the Knowledge Builder. Knowledge Packages are self-contained and serializable, and they currently form the basic deployment unit.

Note

A Knowledge Package instance cannot be reused once it's added to the Knowledge Base. If you need to add it to another Knowledge Base, serialize it and use the "cloned" result.

9.4. Creating a new KnowledgeBase

Procedure 9.2. Task

  1. Use this default configuration to create a new KnowledgeBase:
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    Copy to Clipboard Toggle word wrap
  2. If a custom class loader was used with the KnowledgeBuilder to resolve types not in the default class loader, then that must also be set on the KnowledgeBase. The technique for this is the same as with the KnowledgeBuilder and is shown below:
    KnowledgeBaseConfiguration kbaseConf =
        KnowledgeBaseFactory.createKnowledgeBaseConfiguration( null, cl );
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase( kbaseConf );
    Copy to Clipboard Toggle word wrap

9.5. In-Process Building and Deployment

In-process building is the simplest form of deployment. It compiles the knowledge definitions and adds them to the Knowledge Base in the same JVM. This approach requires drools-core.jar and drools-compiler.jar to be on the classpath.

9.6. Add KnowledgePackages to a KnowledgeBase

Procedure 9.3. Task

  • To add KnowledgePackages to a KnowledgeBase, use this code:
    Collection<KnowledgePackage> kpkgs = kbuilder.getKnowledgePackages();
    
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages( kpkgs );
    Copy to Clipboard Toggle word wrap
    The addKnowledgePackages(kpkgs) method can be called iteratively to add additional knowledge.

9.7. Building and Deployment in Separate Processes

Both the KnowledgeBase and the KnowledgePackage are units of deployment and serializable. This means you can have one machine do any necessary building, requiring drools-compiler.jar, and have another machine deploy and execute everything, needing only drools-core.jar.

9.8. Writing the KnowledgePackage to an OutputStream

This is the code for writing the KnowledgePackage to an OutputStream:
 ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream( fileName ) );
out.writeObject( kpkgs );
out.close();
Copy to Clipboard Toggle word wrap

9.9. Reading the KnowledgePackage from an InputStream

Use this code for reading the KnowledgePackage from an InputStream:
ObjectInputStream in = new ObjectInputStream( new FileInputStream( fileName ) );
// The input stream might contain an individual
// package or a collection.
@SuppressWarnings( "unchecked" )
Collection<KnowledgePackage> kpkgs =
    ()in.readObject( Collection<KnowledgePackage> );
in.close();

KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kpkgs );
Copy to Clipboard Toggle word wrap

9.10. The JBoss Rules Management System

The JBoss Rules Management system is a repository for KnowledgeBases. It helps to maintain large sets of rules.
Additionally, the system compiles and publishes serialized Knowledge Packages to a URL which is then used to load the packages.

9.11. StatefulknowledgeSessions and KnowledgeBase Modifications

The KnowledgeBase creates and returns StatefulKnowledgeSession objects and can optionally keep references to them.
When KnowledgeBase modifications occur, they are applied against the data in the sessions. This reference is a weak reference and it is also optional. It is controlled by a boolean flag.

9.12. New KnowledgeAgents

This is the code for making a new KnowledgeAgent:
KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent( "MyAgent" );
Copy to Clipboard Toggle word wrap

9.13. Writing the KnowledgePackage to an OutputStream

This is how to write the KnowledgePackage to an OutputStream:
KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent( "MyAgent" );
kagent.applyChangeSet( ResourceFactory.newUrlResource( url ) );
KnowledgeBase kbase = kagent.getKnowledgeBase();
Copy to Clipboard Toggle word wrap

Note

Resource scanning is not on by default. It must be started. This also applies to notification. Both can be done via the ResourceFactory.

9.14. Starting the Scanning and Notification Services

This is the code for starting scanning and notification services:
ResourceFactory.getResourceChangeNotifierService().start();
ResourceFactory.getResourceChangeScannerService().start();
Copy to Clipboard Toggle word wrap

9.15. The ResourceChangeScanner

The ResourceChangeScanner is used to scan for services. The default resource scanning period may be changed via the ResourceChangeScannerService. A suitably updated ResourceChangeScannerConfiguration object is passed to the service's configure() method, which allows for the service to be reconfigured on demand.

9.16. Changing the Scanning Intervals

This is the code to use to change scanning intervals:
ResourceChangeScannerConfiguration sconf =
    ResourceFactory.getResourceChangeScannerService().newResourceChangeScannerConfiguration();
// Set the disk scanning interval to 30s, default is 60s.
sconf.setProperty( "drools.resource.scanner.interval", "30" ); 
ResourceFactory.getResourceChangeScannerService().configure( sconf );
Copy to Clipboard Toggle word wrap

9.17. Interactions Between Knowledge Agents and Knowledge Bases

Knowledge Agents can process both an empty Knowledge Base or a populated one. If a populated Knowledge Base is provided, the Knowledge Agent will run an iterator from Knowledge Base and subscribe to the resources that it finds. While it is possible for the Knowledge Builder to build all resources found in a directory, that information is lost by the Knowledge Builder so that those directories will not be continuously scanned. Only directories specified as part of the applyChangeSet(Resource) method are monitored.
One of the advantages of providing KnowledgeBase as the starting point is that you can provide it with a KnowledgeBaseConfiguration. When resource changes are detected and a new KnowledgeBase object is instantiated, it will use the KnowledgeBaseConfiguration of the previous KnowledgeBase object.

9.18. Using an Existing KnowledgeBase

This is the code for utilizing an existing KnowledgeBase:
KnowledgeBaseConfiguration kbaseConf =
    KnowledgeBaseFactory.createKnowledgeBaseConfiguration( null, cl );
KnowledgeBase kbase KnowledgeBaseFactory.newKnowledgeBase( kbaseConf );
// Populate kbase with resources here.

KnowledgeAgent kagent =
    KnowledgeAgentFactory.newKnowledgeAgent( "MyAgent", kbase );
KnowledgeBase kbase = kagent.getKnowledgeBase();
Copy to Clipboard Toggle word wrap
In the above example getKnowledgeBase() will return the same provided kbase instance until resource changes are detected and a new Knowledge Base is built. When the new Knowledge Base is built, it will be done with the KnowledgeBaseConfiguration that was provided to the previous KnowledgeBase.

9.19. The applyChangeSet() Method

If a ChangeSet XML is used with the applyChangeSet() method it will add any directories to the scanning process. When the directory scan detects an additional file, it will be added to the Knowledge Base. Any removed file is removed from the Knowledge Base, and modified files will be removed from the Knowledge Base.

9.20. ChangeSet XML to Add Directory Contents

Use this XML to add the contents of a directory to a ChangeSet:
<change-set xmlns='http://drools.org/drools-5.0/change-set'
            xmlns:xs='http://www.w3.org/2001/XMLSchema-instance'
            xs:schemaLocation='http://drools.org/drools-5.0/change-set.xsd' >
   <add>
      <resource source='file:/projects/myproject/myrules' type='PKG' />
   </add>
</change-set>
Copy to Clipboard Toggle word wrap

Note

Note that for the resource type PKG, the drools-compiler dependency is not needed. The Knowledge Agent is able to handle those with just drools-core.

9.21. The KnowledgeAgentConfiguration Property

The KnowledgeAgentConfiguration can be used to modify a Knowledge Agent's default behavior. You can use this to load the resources from a directory while inhibiting the continuous scan for changes of that directory.

9.22. Change the Scanning Behavior

Use this code to change the scanning behavior:
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

KnowledgeAgentConfiguration kaconf =
    KnowledgeAgentFactory.newKnowledgeAgentConfiguation();
// Do not scan directories, just files.
kaconf.setProperty( "drools.agent.scanDirectories", "false" );
KnowledgeAgent kagent =
    KnowledgeAgentFactory.newKnowledgeAgent( "test agent", kaconf );
Copy to Clipboard Toggle word wrap

Volver arriba
Red Hat logoGithubredditYoutubeTwitter

Aprender

Pruebe, compre y venda

Comunidades

Acerca de la documentación de Red Hat

Ayudamos a los usuarios de Red Hat a innovar y alcanzar sus objetivos con nuestros productos y servicios con contenido en el que pueden confiar. Explore nuestras recientes actualizaciones.

Hacer que el código abierto sea más inclusivo

Red Hat se compromete a reemplazar el lenguaje problemático en nuestro código, documentación y propiedades web. Para más detalles, consulte el Blog de Red Hat.

Acerca de Red Hat

Ofrecemos soluciones reforzadas que facilitan a las empresas trabajar en plataformas y entornos, desde el centro de datos central hasta el perímetro de la red.

Theme

© 2025 Red Hat