Thursday, September 25, 2014

Drools : First Project in Kepler

Drools 6 : Environment Setup in Eclipse Kepler

To create drools project, navigate to File à New à Other.

Now it will open project wizard, in that select Drools à Drools Project and click next.


Enter project name and click next.


Now it will open create new drools project wizard, just click next.
(Selected options will create sample code for us.)


On Drools Runtime Wizard, select ‘Drools 5.1.x or above’ or ‘Drools 6.0.x’ for ‘Generate code compatible with’ field.

Note: Drools 6.0.x (Maven Project) is require ‘GroupId’, ‘ArtificatId’ and ‘Version’ fields.


I have selected ‘Drools 5.1.x or above‘ and click Finish.


Now, Drools project is created with DroolsTest.java and Sample.drl files.
And we have compilation errors.

So Right click on project, Select Build Path à Configure Build Path



Now add, following jars using Add External JARS and click Ok.
drools-compiler-6.1.0.Final.jar
drools-core-6.1.0.Final.jar
drools-reteoo-6.1.0.Final.jar
jbpm-flow-6.1.0.Final.jar
jbpm-flow-builder-6.1.0.Final.jar
knowledge-api-6.1.0.Final.jar
slf4j-simple-1.7.7.jar



Now project is ready with no errors.

Lets run DroosTest.java as Java Application, Just Righclick on DroolsTest.java Run As à Java Application.

Hurray, it is showing the output in console

Hello World
Goodbye cruel world

Here I am giving the Sample Java Code and Rule code with small modifications for reference.

MessageStatus.java
package com.sample;

public enum MessageStatus {
       HELLO, GOODBYE
}

Message.java
package com.sample;

public class Message {
       private MessageStatus status;
       private String message;
       public MessageStatus getStatus() {
              return status;
       }
       public void setStatus(MessageStatus status) {
              this.status = status;
       }
       public String getMessage() {
              return message;
       }
       public void setMessage(String message) {
              this.message = message;
       }
}

DroolsTest.java
package com.sample;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;

/**
 * This is a sample class to launch a rule.
 */
public class DroolsTest {

       public static final void main(String[] args) {
              try {
                     // load up the knowledge base
                     KnowledgeBase kbase = readKnowledgeBase();
                     StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
                     KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
                     // go !
                     Message message = new Message();
                     message.setMessage("Hello World");
                     message.setStatus(MessageStatus.HELLO);
                     ksession.insert(message);
                     ksession.fireAllRules();
                     logger.close();
              } catch (Throwable t) {
                     t.printStackTrace();
              }
       }

       private static KnowledgeBase readKnowledgeBase() throws Exception {
              KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
              kbuilder.add(ResourceFactory.newClassPathResource("Sample.drl"), ResourceType.DRL);
              KnowledgeBuilderErrors errors = kbuilder.getErrors();
              if (errors.size() > 0) {
                     for (KnowledgeBuilderError error : errors) {
                           System.err.println(error);
                     }
                     throw new IllegalArgumentException("Could not parse knowledge.");
              }
              KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
              kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
              return kbase;
       }
}

Sample.drl
package com.sample

import com.sample.Message;
import com.sample.MessageStatus;

rule "Hello World"
    when
        m : Message( status == MessageStatus.HELLO, myMessage : message )
    then
        System.out.println( myMessage );
        m.setMessage( "Goodbye cruel world" );
        m.setStatus( MessageStatus.GOODBYE );
        update( m );
end

rule "GoodBye"
    when
        Message( status == MessageStatus.GOODBYE, myMessage : message )
    then
        System.out.println( myMessage );
end

Note : Please see environment setup post before this.

Drools 6 : Environment Setup in Eclipse Kepler


1.       Download droolsjbpm-integration-distribution-6.1.0.Final.zip from http://www.drools.org.
2.       Download jbpm-6.1.0.Final-bin.zip from http://www.jbpm.org/.
3.       Create folder drools with droolsjbpm, jbpm and jars subfolders in Local_Drive.
4.       Extract droolsjbpm-integration-distribution-6.1.0.Final.zip into C:/drools/droolsjbpm folder.
5.       Extract jbpm-6.1.0.Final-bin.zip into C:/drools/jbpm folder.
6.       Download or Copy following jars into C:/drools/jars folder.
drools-compiler-6.1.0.Final.jar
drools-core-6.1.0.Final.jar
drools-reteoo-6.1.0.Final.jar
jbpm-flow-6.1.0.Final.jar
 jbpm-flow-builder-6.1.0.Final.jar
knowledge-api-6.1.0.Final.jar
slf4j-simple-1.7.7.jar 
7.       Open Eclipse.
8.       Select Help à Install New Software
9.       Enter “Drools - http://download.jboss.org/drools/release/6.1.0.Final/org.drools.updatesite/” in Work with and select Add and Ok.
10.   Check ‘Drools and jBPM’ click Next and Finish.
11.   Select Window à Preferences à  Drools à Installed Drools Runtimes
12.   Click Add and Enter Drools 6 Runtime and C:\drools\droolsjbpm\binaries for Name and Path.
13.   Click Ok and Check Drools 6 Runtime and Apply and Ok.
14.   Select Window à Preferences à jBPM à Installed jBPM Runtimes
15.   Click Add and Enter jBPM 6 Runtime and C:\drools\jbpm for Name and Path
16.   Click Ok and Check jBPM 6 Runtime and Apply and Ok.
17.   Restart the eclipse.

Wednesday, September 17, 2014

Threads : Creating a thread in java using Runnable or Thread


To create a simple thread, we need to following steps:
  1.   Write a class and implements Runnable or extends Thread class.
  2.  Override run method. (This method is called when we start the thread).

If you extends Thread:
public class SimpleThread extends Thread {
       @Override
       public void run() {
              System.out.println("Simple Thread");
       }

       public static void main(String[] args) {
              new SimpleThread().start();
       }
}

Note: This is not a best practice as it will stop you to inherit other classes.

If you implements Runnable:
public class RunnableThread implements Runnable {

       @Override
       public void run() {
              System.out.println("Runnable Thread.");
       }

       public static void main(String[] args) {
              new Thread(new RunnableThread()).start();
       }
}
Note: Here, we pass the class instance to thread class and remaining things are same.
And it is best practice suggested by experts.


Thursday, September 11, 2014

Java 8 : Streams Creation

import java.math.BigInteger;
import java.util.regex.Pattern;
import java.util.stream.Stream;

public class StreamCreation {
       @SuppressWarnings(value = { "all" })
       public static void main(String[] args) {
              String contents = "public class StreamCreation {public static void main(String[] args) {String contents = \"\";}}";
              Stream words = Stream.of(contents.split("[\\P{L}]+"));
              words.forEach(System.out::println);
              Stream songs = Stream.of("gently", "down", "the", "stream");
              songs.forEach(System.out::println);
              Stream silence = Stream.empty();
              silence.forEach(System.out::println);
              Stream echos = Stream.generate(() -> "Echo");
              //echos.forEach(System.out::println);//commented as this are unlimited
              Stream randoms = Stream.generate(Math::random);
              //randoms.forEach(System.out::println);//commented as this are unlimited
              Stream integers = Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE));
              //integers.forEach(System.out::println);//commented as this are unlimited
              Stream wordStream = Pattern.compile("[\\P{L}]+").splitAsStream(contents);
              //using limit on unlimited streams.
              Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE)).limit(10).filter(n-> n.doubleValue()%2==0).forEach(System.out::println);
       }

}

Java 8 : Static Methods

From Java 8, you are allowed to add static methods to interfaces.

Up to Now, it has been common to place static methods in companion classes like Collections for 
Collection interface.

Simply, you will add utility methods to interface as static methods to avoid pairs of classes.

Sample Utility Class :

public interface NumberUtils {
       public static boolean isEven(int number) {
              return (number % 2 == 0);
       }

       public static boolean isOdd(int number) {
              return (number % 2 == 1);
       }

       public static boolean isDivisible(int number, int divisor) {
              return (number % divisor == 0);
       }

       public static boolean isPrime(int number) {
              if (number < 2 || (number > 2 && (number % 2 == 0))) {
                     return false;
              }
              int limit = number / 2;
              for (int i = 2; i < limit; i++) {
                     if (i * i >= number) {
                           limit = i;
                           break;
                     }
              }
              for (int i = 2; i <= limit; i++) {
                     if (number % i == 0) {
                           return false;
                     }
              }
              return true;
       }
}

Java 8 : Default Methods

This are methods declared only in interfaces with ‘default’ keyword to provide default implementation.

public interface DefaultInterface {
       default public void method() {
              System.out.println("Default implementation");
       };
}

This type interfaces will not force classes to implement the interface methods and they provide implementation.

These interfaces helps designers to add methods on top level interfaces to add more functionality.

If two interfaces are providing same method (both are default or one with default) then implementation class must override that method.

If you want to use one of your interface method then you can specify that in implementation using “InterfaceClass.super.methodName”.

public interface Name {
       public String getName();

       public default String getString() {
              return "Name : String";
       }
}
public interface Person {
       default String getName() {
              return "Person : Lenin";
       };
}

public class Employee implements Person, Name {
       public String getName() {//must override this method.
              return "Employee : Lenin";
       }
       //getString method is optional as there is no ambiguity.
}

public class Employee implements Person, Name {
       public String getName() {//must override this method.
              return Person.super.getName();//specifying interface method.
       }
//getString method is optional as there is no ambiguity.
}

If some any class implements Employee then getName will called from Employee only.
Here Class wins for this method as it is implemented in Class.

Note:
  1. We can never make default method for Object class methods.
  2. If you add default methods to interface it has no effect on code that worked before there were default methods.