Search code examples
javaexpert-systemjess

Passing Values from Java to Jess


I have to send some values from the Java class which calls the Jess script for processing in the Jess script.

This is my code till now:

int val1=0;
int val2=1;
Rete engine = new Rete();
Value val = engine.batch("abc.clp");
System.out.println("\n"+val);
engine.watchAll();

How do I pass the values val1 and val2? I found this example but it did not help much.


Solution

  • A set of values from a dialog is best put into a POJO which is inserted into working memory and accessed via a deftemplate declared as being derived from a Java class. Using this in rules is straightforward. The POJO may also hold a field for storing results derived by rule firing.

    The script should set up the Jess definitions but it should not call run. This is best done from Java and most certainly after the insert of the fact.

    Below is a minimum example showing all of the aforesaid.

    import jess.*;
    public class Main {
        public static void main( String[] args ) throws Exception {
            Rete rete = new Rete();
            Value val = rete.batch("security.clp");
            Data data = new Data();
            data.setA( 42 );
            data.setB( 24 );
            rete.add( data );
            rete.run();
            System.out.println( "result = " + data.getRes() );
        }
    }
    

    The POJO class:

    public class Data {
        private int a;
        private int b;
        private String res;
        public void setA( int v ){ a = v; }
        public void setB( int v ){ b = v; }
        public void setRes( String v ){ res = v; }
        public int getA(){ return a; }
        public int getB(){ return b; }
        public String getRes(){ return res; }
    }
    

    The clp file, (modified to demonstrate how to access slot values, and added no-loop):

    (clear)
    (deftemplate Data (declare (from-class Data)))
    (defrule matchab
       (declare (no-loop TRUE))
       ?data <- (Data {a > b} (b ?b))
    =>
       (printout t (fact-slot-value ?data a) " and " ?b crlf)  
       (modify ?data (res agtb))
    )