Drools Expert read rules from String and Database

All samples read their rules from a drl textfile, in a real production rather unlikely to happen. You would rather read the rules from a DB and add it to the Knowledgebase. The add method syntax is public void add(Resource rsrc, ResourceType rt) and does not support a String as a parameter. So here the workaround to convert a String (that you would read from DB) to a resource.

        // read rule from String
        String myRule = "import hellodrools.Message rule \"Hello World 2\" when message:Message (type==\"Test\") then System.out.println(\"Test, Drools!\"); end";
        Resource myResource = ResourceFactory.newReaderResource((Reader) new StringReader(myRule));
        kbuilder.add(myResource, ResourceType.DRL);

Please note: Drools rules dont need a carriage return, only for simplicity I dropped them here.

Up to you where you retrieve the String from, read from DB, XML, user input,…

I have noticed the previous tutorial I was using some kind of legacy packages. It works but is not in sync with the current Drools Documentation and samples. So here the updated HelloDrools code.


package hellodrools;

import java.io.Reader;
import java.io.StringReader;
import java.util.Collection;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.definition.KnowledgePackage;
import org.drools.io.Resource;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;

public class HelloDroolsNew {

    private static KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    private static Collection<KnowledgePackage> pkgs;
    private static KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    private static StatefulKnowledgeSession ksession;

    public static void main(final String[] args) {

        initDrools();
        initMessageObject();
        fireRules();

    }

    private static void initDrools(){

        // this will parse and compile in one step
        // read from file
        kbuilder.add( ResourceFactory.newClassPathResource( "/hellodrools/testrules.drl",HelloDroolsNew.class),ResourceType.DRL );

        // read second rule from String
        String myRule = "import hellodrools.Message rule \"Hello World 2\" when message:Message (type==\"Test\") then System.out.println(\"Test, Drools!\"); end";
        Resource myResource = ResourceFactory.newReaderResource((Reader) new StringReader(myRule));
        kbuilder.add(myResource, ResourceType.DRL);

        // Check the builder for errors
        if ( kbuilder.hasErrors() ) {
            System.out.println( kbuilder.getErrors().toString() );
            throw new RuntimeException( "Unable to compile drl\"." );
        }

        // get the compiled packages (which are serializable)
        pkgs = kbuilder.getKnowledgePackages();

        // add the packages to a knowledgebase (deploy the knowledge packages).
        kbase.addKnowledgePackages( pkgs );

        ksession = kbase.newStatefulKnowledgeSession();
    }

    private static void fireRules(){
        ksession.fireAllRules();
    }

    private static void initMessageObject() {
        Message msg = new Message();
        msg.setType("Test");
        ksession.insert(msg);
    }
}

Netbeans running the Drools samples

Drools is closer to Eclipse because there is a plugin that supports Drools projects with flows, rules, etc. I still prefer Netbeans because it is our corporate IDE of choice and we can live without the visualization or the syntax highlighting of drl files.
The Drools distribution file (download from here)  comes with a bunch of samples that helps you get going with your own projects, usually easier to get hands-on code than to read AI style documentation. Samples and tutorials are for the rest of us.

Netbeans is smart enough to open the examples folder as maven project.

Open Maven Project

When you open the project the first time it will open as “unloadable” because of the missing dependencies. Just right-click on the project “resolve problems” and “prime” the project which will download all the required libraries.

Then you can execute the individual samples (Run File). Voila !

Running the examples

Getting started with Drools and Netbeans

Rule engines are a rather complex topic with potentially a steep learning curve. I am looking at a few options, Drools being one of them. As usual one can read all the theoretical papers, but rather I have a something to look at and play with fast. Ultimately I need to integrate the rule engine into my application, so I dont want to play with eclipse editors for rules but seeing a rule engine ticking inside my Netbeans project. I found one tutorial from Vishal Akhouri which I updated to the latest version of Drools and some minor fixes. Most of the sample source code is from Vishal.

Pre-Requirements:

Tutorial:

ZK goes EC2 (Part 3)

The third part of the tutorial where I improve a few things. I will not walk through the complete code but highlight a few important points and give you the complete sourcecode at the end.

To recap, my requirements:

  • I want to allow users in my company to start and stop instances on their own without them login to AWS console.
  • Only specific instances are available to them.
  • Avoid using elastic IP’s (you pay for them if they are not assigned)
  • Make it configurable

The improvements in this version:

  • Remove the hardcoded access keys and place them encrypted in a properties file.
  • Only instances that are not protected can be started or stopped.
  • Update DynDNS entries from the application
  • Some cosmetic cleanup of the control panel

Continue reading

Netbeans + Visual Paradigm = EJB Tutorial (Part 3)

In part 1 of this tutorial we created an EJB using Netbeans and Visual Paradigm, in part 2 a little ZK application to read data using the EJB. In part 3 we will move away from the Derby DB to PostgreSQL and Oracle DB and challenge ourselves with identifier more than 30 characters, which is an issue for Oracle (yes, it is 2011). We will add columns with more than 30 characters and play with a few different column types (the ones showing up in a normal DB layout).

  • Add new fields to the ERD
    this_is_a_very_long_remark_field
    floatcol
    numbercol

    Updated ERD

  • Continue reading

Netbeans + Visual Paradigm = EJB Tutorial (Part 2)

In part 1 of this tutorial we walk through the modeling and code creation of an EJB using Netbeans and Visual Paradigm. In part 2 we will create a simple sample ZK web application that reads data using the EJB.

Prerequisites:

  • The project from completed tutorial part 1

Tutorial:

ZK goes EC2 (Part 2)

Part 1 of this tutorial we concluded with an web application that displays all our instances and their status. In this part we will add some more features to control our instances.

Prerequisites:

  • The project and environment from part 1

Tutorial (complete sourcecode at the end):

  • Display the region endpoints and allow to select different one
    We hardcoded our endpoint in the first version, if you run instances across the globe in the various AWS datacentres (US, Ireland, Singapore, Tokyo) we need to switch the endpoint easily.
    Lets add one more listbox, that we hide in a ZK popup (we could use a combo listbox, but for the sake of playing with all the available ZK components I use the popup). Same concept add a listbox in the zul and a EC2 region list and a list model with customer renderer in our controller. Continue reading