Setting up a stateful rule session
A stateful rule session can be created according to JSR-94 specifications.
JSR-94 specify that you have to:
- load and get the RuleServiceProvider object
- get the RuleAdministrator object
- load rules by creating a RuleExecutionSet object; this object may be created by means of (i) an XML file to load or (ii) using LocalRuleExecutionSetProvider.createRuleExecutionSet method, passing to it a list of RuleImpl objects
- create a RuleRuntime object
- create the StatefulRuleSession object from the RuleRuntime
This is a java example showing the creation of a StatefulRuleSession object.
try {
// Load the rule service provider of the reference implementation.
// Loading this class will automatically register this provider with the provider manager.
Class.forName( "org.jruleengine.RuleServiceProviderImpl" );
// get the rule service provider from the provider manager
RuleServiceProvider serviceProvider = RuleServiceProviderManager.getRuleServiceProvider( "org.jruleengine" );
// get the RuleAdministrator
RuleAdministrator ruleAdministrator = serviceProvider.getRuleAdministrator();
System.out.println("\nAdministration API\n");
System.out.println( "Acquired RuleAdministrator: " + ruleAdministrator );
// get an input stream to a test XML ruleset
InputStream inStream = new FileInputStream( "example1.xml" );
System.out.println("Acquired InputStream to example1.xml: " + inStream );
// parse the ruleset from the XML document
RuleExecutionSet res1 = ruleAdministrator.getLocalRuleExecutionSetProvider( null ).createRuleExecutionSet( inStream, null );
inStream.close();
System.out.println( "Loaded RuleExecutionSet: " + res1);
// register the RuleExecutionSet
String uri = res1.getName();
ruleAdministrator.registerRuleExecutionSet(uri, res1, null );
System.out.println( "Bound RuleExecutionSet to URI: " + uri);
// Get a RuleRuntime and invoke the rule engine.
System.out.println( "\nRuntime API\n" );
RuleRuntime ruleRuntime = serviceProvider.getRuleRuntime();
System.out.println( "Acquired RuleRuntime: " + ruleRuntime );
// create a StatefulRuleSession
StatefulRuleSession statefulRuleSession =
(StatefulRuleSession) ruleRuntime.createRuleSession( uri,
new HashMap(),
RuleRuntime.STATEFUL_SESSION_TYPE );
// use it...
// Release the session.
statefulRuleSession.release();
}
catch (NoClassDefFoundError e) {
if (e.getMessage().indexOf("Exception") != -1) {
System.err.println("Error: The Rule Engine Implementation could not be found.");
}
else {
System.err.println("Error: " + e.getMessage());
}
}
catch (Exception e) {
e.printStackTrace();
}
|