Hibernate – How To Map Two Collections of The Same Type in The Same Entity

Recently during development, I encountered a situation where I had to map two collections in the same entity, having collections and the entity it self of the same type.

I had persistent entity – Rule. Rule could have children rules: “action” rules and “else” rules. Children rules were also of type Rule.

Basically it was a one-to-many relationship mapping of an entity to itself twice:
Entity Rule could have two different collections of the same object type – Rule. The collections represented “action” and “else” rules.

The challenge that I faced was during XML generation of the persisted entity Rule:

I could successfully persist entity Rule with its children Rules to DB. But, when I was generating the XML, Hibernate was not able to differentiate between “action” and “else” rules and was adding every child Rule to each collection. This was causing the same entity to appear once in each collection:

<?xml version="1.0" encoding="UTF-8"?>
<Rule id="1">
	<ruleType>-1</ruleType>
	<actionChildren>
		<rule>1</rule>
		<rule>2</rule>
	</actionChildren>
	<elseChildren>
		<rule>1</rule>
		<rule>2</rule>
	</elseChildren>
</Rule>

I needed to “tell” somehow to Hibernate which child entity Rule should be added to which collection. I am not sure if my solution is the best in this case, but I created a discriminator property inside entity Rule – “ruleType”.

Respectively, in HBM file, in the mappings of one-to-many relationships, I specified by using SQL query, which rules should be added to the collection when XML is generated. The SQL query was inside where attribute of <list> element.

It done the trick for me – when I was adding a child rule to a parent entity, I was specifying child rule type. Therefore, Hibernate was generating XML correctly by adding “action” rules and “else” rules to their respective collections.

Here is entity Rule:

package org.example.rules;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Rule implements
			Serializable {

private static final long
	serialVersionUID = -76784L;

private int idx;
private int ruleType = -1;
private Rule parentRule = null;

private List<Rule> actionChildren =
		new ArrayList<Rule>();

private List<Rule> elseChildren =
		new ArrayList<Rule>();

/**
 * Default constructor
 */
public Rule() {

}

/**
 * @return the 'action' children
 */
public List<Rule> getActionChildren() {
	return actionChildren;
}

/**
 * @param children
 *            'action' children to set
 */
public void setActionChildren(List<Rule> actionChildren) {
	this.actionChildren = actionChildren;
}

/**
 * @return the 'else' children
 */
public List<Rule> getElseChildren() {
	return elseChildren;
}

/**
 * @param children
 *            'else' children to set
 */
public void setElseChildren(List<Rule> elseChildren) {
	this.elseChildren = elseChildren;
}

/**
 * Adds an 'action' child to the current rule
 *
 * @param actionChild
 *            The rule to be added as a child
 */

public void addActionChild(Rule actionChild) {
	if (!this.actionChildren.contains(actionChild)) {
		actionChild.setParentRule(this);
		this.actionChildren.add(actionChild);
	}
}

/**
 * Adds an 'else' child to the current rule
 *
 * @param elseChild
 *            The rule to be added as a child
 */

public void addElseChild(Rule elseChild) {
	if (!this.elseChildren.contains(elseChild)) {
		elseChild.setParentRule(this);
		this.elseChildren.add(elseChild);
	}
}

/**
 * @return the ruleType
 */
public int getRuleType() {
	return ruleType;
}

/**
 * @param ruleType
 *            the ruleType to set
 */
public void setRuleType(int ruleType) {
	this.ruleType = ruleType;
}

/**
 * @return collection index
 */
public int getIdx() {
	return idx;
}

/**
 * Sets collection index
 * @param collection index
 */
public int setIdx(int idx) {
	this.idx = idx;
}

/**
 * @return parent rule of the current rule
 */
public Rule getParentRule() {
	return parentRule;
}

/**
 * @param ruleParent
 *            the ruleParent to set
 */
public void setParentRule(Rule parentRule) {
	this.parentRule = parentRule;
}
}

Rule HBM file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="org.example.rules.Rule"
	table="org_example_rules_Rule" node="Rule">

<id name="id" column="id" node="@id"
			unsaved-value="0">
	<generator class="native" />
</id>

<!--
Used to help Hibernate to discriminate
between children rules
-->
<property name="ruleType" column="ruleType"
								node="ruleType" />
<!--
Attribute 'where' holds SQL query used to help Hibernate
to discriminate between children rules of type 'action'
and children rules of type 'else'.

Since two children rule lists in the current HBM are of
the same type (org.example.rules.Rule), Hibernate needs
a 'hint' how to discriminate which rules belong to
which list when XML is generated.

If ruleType equals to '1', it means that the child
rule is 'action' rule.

If ruleType equals to '2', it means that the child
rule is 'else' rule.
-->
<list name="actionChildren" embed-xml="true"
		where="ruleType=1" cascade="all">

	<key column="parentrule_id" />
	<list-index column="idx" base="0" />
	<one-to-many class="org.example.rules.Rule"
		node="rule" embed-xml="false" />
</list>

<!--
If ruleType equals to '2', it means that the child
rule is 'else' rule.
-->
<list name="elseChildren" embed-xml="true"
		where="ruleType=2" cascade="all">

	<key column="parentrule_id" />
	<list-index column="idx" base="0" />
	<one-to-many class="org.example.rules.Rule"
		node="rule" embed-xml="false" />

</list>

<!--
Read-only index column, represents position of
the element in the list
-->
<property name="idx" column="idx" node="idx"
		update="false" insert="false" type="int" />

<!--
Embed XML must be equals to 'false',
otherwise when XML is generated for
children rules, parent XML will be
generated recursively
-->
<many-to-one name="parentRule" node="parentRule"
	column="parentrule_id" class="org.example.rules.Rule"
	not-null="false" insert="false" update="false"
	embed-xml="false" />

</class>
</hibernate-mapping>

Generally, I would not advise to design persistent entities in this way, it can create problem later on. For example if there is a need to delete child entities. It can become a bit tricky, since entity has relationship to it self.

Suggestions? Flames?

Brainteaser: Hidden Iterators

… While locking can prevent iterators from throwing ConcurrentMofdificationException, You have to remember to use locking everywhere a shared collection might be iterated. This is trickier than it sounds …

Brian Goetz p.83-84

Question: The following code could throw ConcurrentMofdificationException, even though add() is synchronized, why?

public class HiddenIterator  {
     private final Set set = new HashSet();

public synchronized void add(Integer i) {
     set.add(i);
}

public synchronized void remove(Integer i) {
     set.remove(i);
}

public void addTenThings() {
   Random r = new Random();
   for (int index = 0; index &lt; 10;  index++;) {
       add(r.nextInt());
   }

   System.out.println("Added ten elements to set: " + set);
}
}

Looking forward for your answers dear readers

Singleton Pattern and Problem With Double Checked Locking

There are several ways to initialize singleton object. Some are thread safe and some are not. Until the last two days I thought that double-checked locking idiom offers the best solution for singleton initialization in multi threaded environment. Well its not.

To begin, I want to describe briefly several ways to initialize singleton:

  • Lazy initialization
  • Eager initialization
  • DCL
  • Class holder lazy initialization
  • Enum singleton

Lazy initialization
The goal of lazy initialization was to defer initialization of an object until it is actually needed, while making sure that initialization is done only once. Lazy initialization example illustrated below:

public class Singleton{

	private static Singleton instance = null;

	private Singleton() {  }

	public static Singleton getInstance() {
		if (instance == null)  {
		instance = new Singleton();
	}
        return instance;
    }
}

This will work fine in single-threaded environment. Unfortunately since getInstance() is not synchronized, two different instances of the object can be returned if two threads will access getInstance() method concurrently. Which makes this lazy initialization unsafe in multi threaded environment.

Unsafe lazy initialization can be fixed by making getInstance() synchronized:


	public class Singleton{

	private static Singleton instance = null;

	private Singleton() {  }

	public static synchronized Singleton getInstance() {
		if (instance == null)  {
			instance = new Singleton();
		}
		return instance;
	}
	}

However, in this case there is performance hit for every invocation of getInstance() method. Synchronized methods runs very slow compared to unsynchronized methods. I haven’t tested this issue my self, so i cannot tell by how much slower.

Eager initialization
By using eager initialization, the synchronization cost incurred for each method call is eliminated:

	public class Singleton{
		private static Singleton instance = new Singleton();

		private Singleton() {  }

		public static Singleton getInstance() {
			return instance;
		}
	}

The problem with eager initialization that Singleton object is instantiated regardless whether it is going to be used or not.

DCL
Double-checked locking (DCL) idiom was created to allow lazy initialization of a singleton object, without performance reducing costs as a result of synchronization. Unfortunately it does not work. Lets have a look why:

public class Singleton {

  private static Singleton instance = null;

  private Singleton() {  }

  public static Singleton getInstance() {
	if (instance == null)  {
		synchronized(Singleton.class)  {
			if (instance == null)  {
				instance = new Singleton();
			}
		}
	}
	return instance;
	}
}

First there is a check whether initialization is needed with out synchronization, and if the instance is not null – then use it.
Otherwise, synchronize and check again if instance is null by making sure that only one thread will initialize the shared Singleton.

The problem with DCL is that code of fetching reference to constructed Singleton object does not require synchronization.
Lets say that thread ‘a’ has entered synchronized block, made the instance not null but hasn’t executed the constructor yet. At this stage thread ‘b’ preempts thread ‘a’. Thread ‘b’ checks if the instance is not null, and since its not, it returns reference to a partially constructed Singleton object.

In other words – thread ‘b’ sees a current value of the Singleton object reference instead of its stale value, which causes the object to be seen in invalid or incorrect state.

Class holder lazy initialization

Instead of DCL, lazy initialization class holder idiom offers better solution for singleton initialization in multi threaded environment, with the same benefits as DCL:

public class SingletonFactory {

  private static class SingletonHolder {
     public static Singleton instance = new Singleton();
  }

  public static Singleton getInstance()  {
     return SingletonHolder.instance;
  }
}

The SingletonHolder class initialization is deferred until its actually used, and because Singleton is initialized with static initializer, no additional synchronization is needed.
The first invocation of getInstance() by any thread causes SingletonHolder to be loaded and initialized during which time the Singleton is initialized through static initializer.

Enum singleton
Joshua Bloch in his book “Effective Java” offers a new interesting solution to initialize a Singleton by using Enum with a single type:

public class SingletonEnum {
  INSTANCE;

  public void someMethod() {
     ...
  }

  public void anotherMethod() {
     ...
  }
}

Joshua claims:

“…a single-element enum type is the best way to implement a singleton…”

Some people may argue against this approach by saying that this is not a class, but an enum – it enumarates plus enums cannot be subclassed. Well in case of a singleton there is no point in subclassing, since singletons have private constructors and singletons dont really ment to be subclassed. Lets have a look if Enum singleton is indeed the best solution so far:

1. Enum singleton is final
2. It is serializable
3. It is a single instance in multithreaded environment
4. Does not allow invokation of private constructors through reflection attacks

I think its quite original solution.

I will appreciate your comments regarding this post. Cheers.

Resources:
Effective Java
Java Concurrency in Practice

Double-checked locking and the Singleton pattern

Drools – Stop Executing Current Agenda Group and All Rules

Sometimes, depends on your business rules in your application, there is a need to stop current agenda group or all rules from continuing to execute. It wont help setting a focus to another agenda group, since previous agenda will still remain in a stack. So in this post I want to show how to prevent rules in a particular agenda group from continuing to execute by clearing the agenda and also how to stop all rules totally.

Please note, in this example I am using agenda-groups to drive execution flow.

I created a short DRL file and a DSL template to demonstrate how clearing agenda and stopping of all rules can be achieved.

The DRL file:

expander template.dsl;

/*****************************************
 First default rule to kick in
******************************************/
rule "baserule"
salience 100000
auto-focus true
agenda-group "first-group"
when
      True
then

end

/*****************************************
 Second rule to kick in
******************************************/
rule "1"
salience 1000
agenda-group "first-group"
when
      True
then
      Goto agenda "second-group"
end

/*****************************************
 Third rule to kick in
******************************************/
rule "2"
salience 1000
agenda-group "second-group"
when
      True
then
      Do something
end

/*****************************************
 Fourth rule to kick in

 Current rule stops agenda "second-group"
 from continuing to execute, and the
 focus will be returned back to
 agenda "first-group"
******************************************/
rule "3"
salience 900
agenda-group "second-group"
when
      True
then
      Stop agenda "second-group" //clear current agenda
end

/*****************************************
 This rule never kicks in, since agenda
 "second-group" was cleared by rule "3"
******************************************/
rule "4"
salience 800
agenda-group "second-group"
when
      True
then
      Do something
end

/*****************************************
 Fifth rule to kick in

 After clearing agenda "second-group", the
 focus will be returned here
******************************************/
rule "5"
salience 900
agenda-group "first-group"
when
      True
then
      Do something
end

/*****************************************
 Sixth rule to kick in
 Current rule stops execution of all rules
******************************************/
rule "6"
salience 800
agenda-group "first-group"
when
      True
then
      Stop all
end

/*****************************************
 This rule never kicks in, since all rules
 execution was stopped by rule "6"
******************************************/
rule "7"
salience 700
agenda-group "first-group"
when
      True
then
      Do something
end

The DSL template:

[when]True=eval(true)
[then]Do something=
      System.out.println("Doing something");
[then]Stop all=drools.halt();
[then]Goto agenda "{agenda}"=
      drools.setFocus( "{agenda}" );
[then]Stop agenda "{agenda}"=
      drools.getWorkingMemory().
		clearAgendaGroup("{agenda}");

Basically what happens is: once the execution reaches rule “3″, I am calling for clearAgendaGroup() method to clear agenda, hence to remove it from the stack. As a result of the clearing, rule “4″ will never be executed.

When focus is returned back to agenda “first-group”, it lands on rule “5″. When the execution reaches rule “6″, I am calling for drools.halt() method to stop execution of all rules.

Keep in mind that in Drools 3 there is no halt() method. It came with Drools 4. If you want to achieve the above result of stopping all rules in Drools 3, you can call for drools.clearAgenda();

You noticed that I am using “drools” object and calling some methods on that object in my DSL template. Well “drools” object is actually KnowledgeHelper class, which is part of Drools library. It provides several APIs, for example method halt(), setFocus() and getWorkingMemory().

Keep in mind that I did not actually tested these particular DRL and DSL, but this example is based on real scenario that I have tested.

Comments/questions/flames are welcomed

Marshalling VS Serialization

The two terms are very very similar, and often treated the same. Quite few responds on various forums contradict each other, which made me a bit confused. So to make it clear for my self I decided to summarize what i understood from the resources I have read on the Internet:

Serialization:

  1. Technique of converting a state of an object (or object instance in different words) into a byte stream.
  2. To send object over the network, it needs to be serialized first, thus converted into to a sequence of bytes.

Marshalling:

  1. Technique of encoding an object to send it over the network and decoding it on the other end. Which is stub and skeleton mechanism, where stub is the local client and skeleton is the remote server.
  2. Besides the object state, marshalling also records codebases.
  3. Marshalling is used for sending objects through sockets. Off course objects must be serialized serialized before sending over the network.
  4. Marshalling is a way to create byte stream so that the copy of the original object can be recreated on the other side. When object is “unmarshalled” on the other side, object’s class definitions are loaded.
  5. Marshalling is a form of serialization, thats why I think some people treat teh two the same.

Thats it… I think… Did I miss something?

Java Generics and Reflection

Hi, the other day I had a situation, where in my code at run time I had to determine the super type of the Class that I obtained. To sub type my classes, I used generics.

In case my obtained Class was of expected super type, I had to invoke a super class static method on the subclass Class using reflection.

I used these concepts and prepared a short tutorial, I also attached source files to this post in case someone wants to download them. What I did was I created an abstract class, and an extending child class using generics. In my test client, I determine the super type of my child class at run time and then I invoke a static method using reflection.

Reflection also allows to invoke methods, constructors and change value of fields that are private. It is often called “reflection attack”. In my post Hack any Java class using reflection attack, I give several examples about reflection attack.

Ok, back to the topic now:

My abstract parent class:

import java.io.Serializable;
import java.util.Date;

public abstract class AbstractParentEntity
		<E extends AbstractParentEntity>
				implements Serializable {

    private static final
	long serialVersionUID = 5419258598746186610L;

	public static Long getSomeLongValue() {
		return new Long(999);
	}

}

My extending child class:

import java.io.Serializable;

public class ChildEntity extends
	AbstractParentEntity<ChildEntity>
			implements Serializable {

     private static final long
	serialVersionUID = -2271176823058287608L;

	private String name;

	public ChildEntity()  {

	}
}

My test client:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

public class Test {

	//canonical name of my child class
	private static final String
		CHILD_CLASS_NAME = "ChildEntity";
	//name of the static method i am going to invoke
	private static final String
		PARENT_METHOD = "getSomeLongValue";

   public static void main(String[] args) {

	Thread thread = Thread.currentThread();

	ClassLoader classLoader =
			thread.getContextClassLoader();

	try {

	//use class loader to create a Class for
	//a given class name
	Class subclass = Class.forName(CHILD_CLASS_NAME,
				true, classLoader);
	System.out.println("Subclass canonical name: ["
		+ subclass.getCanonicalName() + "]");

	//get superclass Class from the subclass
	Class superclass = subclass.getSuperclass();
	System.out.println("Super class canonical name: ["
		+ superclass.getCanonicalName() + "]");

	//get the type of subclass
	Type subtype = subclass.getGenericSuperclass();
	System.out.println("Subclass type: ["
		+ subtype.toString() + "]");

	//check whether my subclass type starts with
	//class name of my super type, if true - my subclass
	//is indeed of type of my superclass
	if (subtype.toString().startsWith(
			superclass.getCanonicalName())) {

	System.out.println("Class: [" +
		subclass.getSimpleName()
		+ "] is type of ["
		+ superclass.getSimpleName() + "]");
	}

	// 'null' assumes empty array
	Method method = subclass.getMethod(PARENT_METHOD,
				(Class[]) null);

	/*
	* public Object invoke(Object obj, Object args)
	*
	* If the underlying method is static, then the specified 'obj'
	* argument is ignored. It may be null.
	*
	* Parameters: obj - the object the underlying method is invoked
	* from args - the arguments used for the method call
	*/

	System.out.println("Invoking static parent method: [" +
		PARENT_METHOD + "] on extending subclass...");
	Object objResult = method.invoke(null, (Object[]) null);

	System.out.println("Some value: [" + objResult.toString() + "]");

	}
	catch (SecurityException e) {
		e.printStackTrace();
	}
	catch (NoSuchMethodException e) {
		e.printStackTrace();
	}
	catch (IllegalArgumentException e) {
		e.printStackTrace();
	}
	catch (IllegalAccessException e) {
		e.printStackTrace();
	}
	catch (InvocationTargetException e) {
		e.printStackTrace();
	}
	catch (ClassNotFoundException e) {
		e.printStackTrace();
	}

	}
}

Basically what happens is: iI compare whether the Type of my subclass: AbstractParentEntity starts with the canonical name of my super class: AbstractParentEntity.

When using generics, this will always return true if my subclass extended from my super class.

When I successfully determined the subclass type, i invoked static method using reflection. Below you can see the output of my program:

Subclass canonical name: [ChildEntity]
Super class canonical name: [AbstractParentEntity]
Subclass type: [AbstractParentEntity<ChildEntity>]
Class: [ChildEntity] is type of [AbstractParentEntity]
Invoking static parent method: [getSomeLongValue] on extending subclass...
Some value: [999]

If you never used generics in Java (those who moved on to Java from C++ will know what generics are), Sun offers a nice generics introduction tutorial which explains the basics.

Basically generics allow you to abstract over types. When you use generics in your code it becomes safer and clearer. So i think it worth while having a pick at it :)

Comments / corrections / flames?

Drools – Working with Stateless Session

Drools (now it is also called JBoss Rules) is an amazing open source framework which allows you to create business rules management system for your application. I got introduced to Drools while working on a project at my current company.

It is very easy to use and implement it and it is very efficient. For example instead of having dozens of if-else statements for some application business rules, you can use Drools to create a rule engine with your defined rules and pass your objects through the rule engine.

For example, in your application that deals with student objects, you can create a rule that checks whether the student has paid his fees for the next semester, if not – send him/her reminder email… etc..

In this example i want to show how to work with Stateless drools session to retrieve results from the global variable. I know that at this point its a bit not clear, so i will try to explain as I go… or you can simply visit their website, the link is under “Useful Links” section on the right hand side…

In addition to that you can always join their IRC channel #drools, the drools team is very helpful and i owe my special thanks to a fellas name mic_hat and conan there, that had a lot of patience for me ;)

For my example i prepared a simple POJO, DRL and DSL files and a test client.
DRL is the file that contains my rules. DSL is the expandable template for DRL.

Drools allow you to write your rules using plain human language in DRL, and then in DSL template you can specify to what programming code the human sentence corresponds to. The following explains what I mean:

My DRL file with 2 rules in it:

package com.test.drools.rules;

expander mydsl.dsl;

import com.test.drools.entities.Pojo;

global java.util.List list;

rule "1"
salience 1000
auto-focus true

when
      The blog name is "Java Beans dot Asia"
then
      Log "The blog name was matched"
end

rule "2"
salience 900

when
      This post was created in "May"
then
      Log "The blog post month was matched"
end

“expander mydsl.dsl” – file name of my DSL template.
“global java.util.List list” – a global variable, which is the type of List. Global variable you can use for storing some results, log messages and even objects.
“salience” – the priority which rules should be executed first.
“auto-focus” – the rule that has auto-focus will get executed first, basically the starting point of execution.

My DSL template file for my DRL:

[condition][]The blog name is "{name}"= poj : Pojo( blogName == "{name}")
[condition][]This post was created in "{month}"= poj : Pojo( postMonth == "{month}")
[consequence][]Log "{message}"= list.add(new String("{message}"));

As you can see “This post was created in “arg”" will expands into “poj : Pojo( postMonth == “{month}”)”, where the value of “arg” will be compared to the value of postMonth variable in my POJO.

Keep in mind that you do not have to use DSL template, you can use only DRL file if you want to and have your source code there. Using the template makes your rules very readable.

My POJO:

package com.test.drools.entities;

import java.io.Serializable;

public class Pojo implements Serializable {

	private String blogName;
	private String postMonth;

	public Pojo() {

	}

	public String getBlogName() {
		return blogName;
	}

	public void setBlogName(String blogName) {
		this.blogName = blogName;
	}

	public String getPostMonth() {
		return postMonth;
	}

	public void setPostMonth(String postMonth) {
		this.postMonth = postMonth;
	}
}

My client:

package com.test.drools.client;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.StatelessSession;
import org.drools.StatelessSessionResult;
import org.drools.base.CopyIdentifiersGlobalExporter;
import org.drools.compiler.DroolsError;
import org.drools.compiler.DroolsParserException;
import org.drools.compiler.PackageBuilder;
import org.drools.compiler.PackageBuilderErrors;

import com.test.drools.entities.Pojo;

public class Client {

//path to the DRL file inside my JAR
final static String DRL_URL =
		"/com/test/drools/rules/mydrl.drl";
//path to the DSL file inside my JAR
final static String DSL_URL =
		"/com/test/drools/rules/mydsl.dsl";

public static void main(String[] args) {

   //Instantiate and initialize the POJO.
   Pojo p1 = new Pojo();
   p1.setBlogName("Java Beans dot Asia");
   p1.setPostMonth("May");

   //Calling for private method to compile a RuleBase
   RuleBase ruleBase = getRuleBase();

   //Instantiating StatelessSession
   StatelessSession session =
			ruleBase.newStatelessSession();

   //Setting global variable:
   //the name 'list' is the same name mentioned in DRL:
   //global java.util.List list;
   session.setGlobal("list", list);

   //specifying the global name that should be exported
   session.setGlobalExporter(
   new CopyIdentifiersGlobalExporter(
				new String[]{"list"} ) );

   //executeWithResults() - stores execution results in
   //StatelessSessionResult object. That objects will
   //contain our global variable with results, that we
   //can use after the execution of stateless
   //session is finished.
   StatelessSessionResult result =
			session.executeWithResults(p1);

   //get global variable and cast back to
   //the type of List
   List retrievedList = (List) result.getGlobal("list");

   if (retrievedList != null &&
			retrievedList.size() > 0) {

   for (Iterator i = retrievedList.iterator();
					i.hasNext();) {
	System.out.println((String) i.next());
   }
}

}

private static RuleBase getRuleBase() {

//Create a new package builder
PackageBuilder builder = new PackageBuilder();

try {

//call for private method to get the DRL
Reader drl = getSourceDrl();

//call for private method to get the DSL
Reader dsl = getDsl();

//Add rule package to the builder using drl and
//dsl Reader objects
builder.addPackageFromDrl(drl, dsl);

//Check whether our DRL and DSL files had any
//errors when trying to create a rule package.
//If DRL and/or DSL had any errors we wont be able
//to create a rule package and a new RuleBase.
PackageBuilderErrors errors = builder.getErrors();

DroolsError[] error = errors.getErrors();

if (error.length > 0) {
for (DroolsError err : error) {
System.out.println("Errors are: " + err.getMessage());
}
}

} catch (DroolsParserException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}

//Get new RuleBase object. RuleBase is where
//we will get Stateless session object from.
RuleBase ruleBase = RuleBaseFactory.newRuleBase();

try {
//Add package with our rules to the RuleBase.
//This is when the RuleBase is actually compiled
ruleBase.addPackage(builder.getPackage());
} catch (Exception e1) {
e1.printStackTrace();
}

return ruleBase;
}

private static Reader getDsl()
			throws IOException {
return new InputStreamReader(Client.class
.getResourceAsStream(DSL_URL));
}

private static Reader getSourceDrl()
			throws IOException {
return new InputStreamReader(Client.class
.getResourceAsStream(DRL_URL));
}

}

I will try to give now a brief explanation what is actually happening:
When session.executeWithResults(p1); is executes, rule engine will apply the rules on a p1 POJO object. If rules will be matched, then the result will be stored in the global variable.

For example:
If value of “blogName” variable inside my p1 POJO object will be equal to “Java Beans dot Asia”, then the rule#1 in my DRL will be matched, and the result “The blog name was matched” will be stored in my global List.

The final output of the program will be as follows:

"The blog name was matched"
"The blog post month was matched"

This example was very simple, I had only two rules where i did comparison of String literals. But Drools definitely has the capability to create a friendly business rule system with thousands of rules if needed, while staying user friendly for both developers and business clients. I think its worth while checking it out :)

I’ve included a source code and jUnit test case for this tutorial if you want to have a look at it and try it your self.

drools – working with stateless session sourcecode

Bitwise Operation In Hibernate 3

Hi all…
i encountered a small problem in doing bitwise operations with hibernate. Until now, HIbernate 2 HQL parser has supported bitwise operations. Hibernate 3 for some reason does not support it. So if you want to work around it, you have to create a custom SQLfunction and add it to the dialect, that will map the bitwise operator.

You have to create your own class, which will extend from StandardSQLFunction class and will implement SQLFunction interface. You have to override render() method from the interface mentioned before and provide your own implementation.

In my example I am showing how to use ampersand symbol (‘&’) for bitwise operation.

Important note:
Hibernate team people have changed SQLFunction interface when upgrading from version 3.0.2 to 3.0.3, so your custom implementation of bitwise operation in version 3.0.2 will not work in 3.0.3. So keep that in mind.

Update (13.Jan.2010):
According to one of the blog reader’s this example has successfully worked under Hibernate v.3.2.6!

Implementation:
I am using Sysbase dialect, so i will create a class that extends this dialect with my own implementation:

package com.project.test.dialect;

import org.hibernate.Hibernate;

public class SybaseDialect extends
	org.hibernate.dialect.SybaseDialect{

	public SybaseDialect() {
	   super();
	   registerFunction("bitwise_and",
		new BitwiseAndFunction("bitwise_and",
				Hibernate.INTEGER));
	} 

}

What it means basically that i am registering a function by the name of bitwise_and the return type will be of type Integer.

Now, my custom class for SQLFunction like this:

package com.project.test.dialect;

import java.util.List;

import org.hibernate.QueryException;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.type.Type;

public class BitwiseAndFunction
		extends StandardSQLFunction
			 implements SQLFunction {

 public BitwiseAndFunction(String name) {
		super(name);
 }

 public BitwiseAndFunction(String name, Type type) {
	super(name, type);
 }

 public String render(List args,
	SessionFactoryImplementor factory)
			throws QueryException {
   if (args.size() != 2) {
      throw new IllegalArgumentException(
	"the function must be passed 2 arguments");
   }
   StringBuffer buffer = new
	StringBuffer(args.get(0).toString());
   buffer.append(" & ").append(args.get(1));
   return buffer.toString();
 }
}

The method render() accepts two arguments, if less – exception will be thrown. Once arguments are passed to the method, it will return a String that will look something like this (assuming that the passed arguments were one (1) and two (2)):

1 & 2

In my project, I am using named queries in my hbm.xml files, so below you can see a part of my hbm.xml file where I use my bitwise function:

<query name="UserPermissionsForEnttiy">
select object(ep) from EntityPermission ep where ep.userid =
:userid and ep.entityid = :entityid and ep.classname =
:classname and bitwise_and(ep.permission,:requiredpermission) > 0
</query>

Note the two arguments that i am passing to the bitwise_and function.

Also not forget to update your persistence XML with your custom dialect class, this is how my persistence.xml looks like:

<persistence>
<persistence-unit name="com.project.test.users">
<jta-data-source>java:/DefaultDS</jta-data-source>
   <properties>
   <property name="hibernate.dialect"
	value="com.project.test.dialect.SybaseDialect"/>
   <property name="hibernate.hbm2ddl.auto"
	value="update"/>
   <property name="hibernate.show_sql"
	value="true"/>
	   .
	   .
	   .
   </properties>
</persistence-unit>
</persistence>

Please note the hibernate.dialect property. As a value i gave the canonical name of my custom SysbaseDialect class.

Once you finished implementing your custom dialect classes, you can JAR them and put into the lib directory of your JBoss instance where the rest of your Hibernate libraries are.

Do not forget to restart your JBoss – it needs to load your newly added JAR, for you to be able to use it ;)

Multiple Return Statements

Yesterday I had a thought in my mind (which is good already to have one) – how many return statements a method should have?

Whats the difference if you have method that looks like that:

public int calculateSum(int a, int b, int c)  {
	int result = -1;
	if (a % b == c)  {
	   result = c;
	}
	else if ((a + b - c) > (a - c))  {
	   result = a;
	}

	return result;
}

or the same method but looks like that:

public int calculateSum(int a, int b, int c)  {
	if (a % b == c)  {
	   return c;
	}
	else if ((a + b - c) > (a - c))  {
	   return a;
	}

	return -1;
}

I always thought (at least this is how i was taught), that having one return statement makes code look more elegant, and i should try to avoid having multiple return statements. When i asked my colleague what he thinks about this, he said that at run time, method with multiple returns will execute faster and the code looks clearer. That sounded logical enough, and after doing some more investigation i have to say that i tend to agree.

Although some may say that having multiple return statements in a method can create a confusion, and it will be hard to see all the exit places. But if this is the case, i would say that maybe the method needs to be re-factored and simplified?

Serialize POJO to XML

Today my colleague, Chandana was trying to convert POJO to an XML file. In our company we are working with dom4j library, but unfortunately it does not provide the capabilities to convert a Java object on the fly to an XML.

Off course Chandana could always manually create new Document, root element, sub elements and attributes and that would work fine. But this still does not solves Chandana’s problem where she needed to generate XML on the fly.

After some time doing a research on the Internet she came across this very nice library call XStream. Its a very nice library which allows to serialize objects to XML and back again. It doesn’t require mapping nor modifications to the object itself. They also have a short tutorial which converts a POJO to an XML in few simple steps. Very nice and usefuL