Search code examples
droolsdrools-guvnordrools-plannerdrools-fusion

How to edit and update the Drools rule file?


My project uses drools expert means (DRL) file. In the rules file, if the user wants to delete and update the rules, what should be done?

Rule file:

package com.sample;

import com.sample.Tuplebean;
import com.sample.DroolsBolt;

dialect "mvel"

rule "SafetyAlert-Critical"
when
    t:Tuplebean(t.getSmoke() == true && t.getSmoke_density() == true && t.getTemperature() > 25.0)
then
    DroolsBolt.insertToAlertLog("alert generated");
end

For example, the user wants to change the value of temperature to 30.0.


Solution

  • In my application i gone through same problem i fixed those problem by fallowing way , i am maintaining the all the rule file database.

    I am keeping all the rule file in tables and i am loading every rule file based on the IMEI number(in my case i am generating one rule for one adaptor ie adaptor having unique IMEI number).

    In below code first load the rule file from datbase and convert that string to the Resource beacuse Resource Factory accept only Resource as constructor argument. and store that in to the ksession and fire the rules.

    For edit and delete operation i make one flag in database , if that flag is true again update the rule file to the database table. if it is false load the same old rule file.

    Here your generating the rule file and save to the database table and if flag is true and again your re-generate the rule file.

    public void generateDrrols(String macAddress) throws SQLException, ClassNotFoundException, IOException{
            logger.error("++++Generate drools file started++++");
            Class.forName("org.postgresql.Driver");
            Connection conn = DriverManager.getConnection("jdbc:postgresql://10.0.0.5:5432/iotdb",
                        "postgres", "track@123");
    
            //String sql="SELECT alert_playload FROM iot.alert_configuration WHERE drools_boolean=true and alert_configuration_id=94 && 95";
             String sql = ""
                  + "select drools_condtion , iot.alert_configuration.alert_status , iot.alert_configuration.websocket_key , device_id , iot.alert_configuration.device_configuration_id , "
                  + "email , iot.alert_configuration.mac_address , phone , sensor_id , iot.alert_configuration.sensor_configuration_id , alert_configuration_id , site_id , "
                  + "startdatetime , enddatetime , exludedays , timetoexclude , log_update_time ,iot.sensor_configuration.sensor_name "
                  + "from iot.alert_configuration "
                  + "join iot.sensor_configuration on iot.sensor_configuration.sensor_configuration_id=iot.alert_configuration.sensor_configuration_id "
                  + "where iot.alert_configuration.mac_address=? and soft_delete_flag=false";
    
             PreparedStatement prepareStatement = conn.prepareStatement(sql);
             prepareStatement.setString(1, macAddress);
             ResultSet rs = prepareStatement.executeQuery();
            //ResultSet rs = sta.executeQuery(sql);
    
            final ResultSetGenerator converter = new ResultSetGenerator();
            InputStream in = getClass().getResourceAsStream("/alert.drt"); 
            final String drl = converter.compile(rs, in);
            System.out.println(drl);
            rs.close();
            KnowledgeBuilder kbuilder =
                  KnowledgeBuilderFactory.newKnowledgeBuilder();
            kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()),
                       ResourceType.DRL);
            KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
            kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
            StatefulKnowledgeSession kSession = 
            kbase.newStatefulKnowledgeSession();
            logger.error("++++Reading rule file ie., rule.drl started++++");
    
            logger.error("++++Making drool table status false++++");
            String sql2="update iot.drool_rules set drool_rules=? where mac_address=?";
            PreparedStatement prepareStatement2 = conn.prepareStatement(sql2);
            prepareStatement2.setString(1, drl.toString());
            prepareStatement2.setString(2, macAddress);
            boolean execute2 = prepareStatement2.execute();
            String sql1="update iot.alert_configuration set storm_drool_status=false where mac_address=?";
            //Statement createStatement = conn.createStatement();
            PreparedStatement prepareStatement3 = conn.prepareStatement(sql1);
            prepareStatement3.setString(1, macAddress);
            boolean execute = prepareStatement3.execute();
    
        }
    

    Here your loaing the rule file from database and fire all the rules.

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        try{
            String sql="select drool_rules from iot.drool_rules where mac_address=?";
            PreparedStatement prepareStatement = connectPostgres.prepareStatement(hql);
            prepareStatement.setString(1, topicId);
            ResultSet executeQuery1 = prepareStatement.executeQuery();
            String rules=null;
            while(executeQuery1.next()){
                rules=executeQuery1.getString(1);
            }
            String i=null;
            String replace = rules.replace('"', '\"');
            System.out.println(replace);
            Reader reader=(Reader)new StringReader(replace);
            Resource myResource = ResourceFactory.newReaderResource(reader);
            kbuilder.add(myResource, ResourceType.DRL);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
            KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
            kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
            ksession = kbase.newStatefulKnowledgeSession();