<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>The Integrallis Blog : Category java, everything about java</title>
    <link>http://www.integrallis.com/blog/category/java.rss</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Musings on Ruby, Groovy, Java and programming in general</description>
    <item>
      <title>Using GORM to Boost Legacy Spring Applications</title>
      <description>&lt;h3&gt;Using GORM with your Spring application can increase the productivity and readability of your code&lt;/h3&gt;

&lt;p&gt;Groovy and Grails has stormed the Java world as the new way to create reliable Web 2.0 applications in a concise and fast manner. The ability to go from the start of a project to the end, especially for a smaller demo, is exponentially faster. This is due to the many features of Grails. Out of the box applications are easier to build, create, test, and deploy because of the convention over configuration methodology. In addition Grails is written in Groovy, a dynamic language that can run on the JVM and interact as if they were Java classes. Groovy gives the power to write dynamic code with power and features that are normally unavailable in Java. Possibly the best example of this power in Groovy and Grails is the creation of the Grails Object Relational Mapper (GORM). &lt;/p&gt;

&lt;p&gt;However, we can&#8217;t all just go to our managers and say &#8220;Hey, let&#8217;s rewrite this entire application in Grails&#8221;. We would more than likely get laughed out the door. At many companies it also isn&#8217;t feasible to ask for an entire framework shift. However, most of us can request &#8220;small changes&#8221;, especially if they help save time. &lt;/p&gt;

&lt;p&gt;With Spring 2.0 and above we can create Spring beans out of Groovy objects. This gives us a nice ability to use Groovy nomenclature in our Spring code (e.g. the Meta Object Programming (MOP), cleaner syntax, etc). However, what we do not get with straight Groovy is a better way to interact with the database. For that we need the power of GORM. With Grails 1.1 that has become significantly easier.&lt;/p&gt;

&lt;h3&gt;Why Do I Want To Use GORM?&lt;/h3&gt;

&lt;p&gt;You may be familiar with Hibernate and wonder why you should bother with GORM. Hibernate is a GREAT ORM, and the framework has been developed steadily since its inception. While Spring&#8217;s wrapping of Hibernate has made it easier to interact with the database, it is still missing the readability and ease of use that most modern developers want.  The following example demonstrates how GORM brings simplicity to Hibernate code. (Please note that although GORM derives from Hibernate any mention of Hibernate here will specifically be in reference to the pure Java Hibernate form.)&lt;/p&gt;

&lt;p&gt;This example starts by performing a simple query to retrieve items from the Todo table in the database where name and description matched some given text. When using Spring&#8217;s Hibernate Template, the code would look something like this:&lt;/p&gt;

&lt;pre class="brush: java;"&gt;
public List find(final String name, final String desc) {
final String hqlQuery =         
    "select t from Todo t where t.name = :name and t.description = :desc";
    return (List) getHibernateTemplate().execute(new HibernateCallback() {
    public Object doInHibernate(Session session) throws HibernateException {
        Query query = session.createQuery(hqlQuery);      
        query.setString("name", name);
        query.setString("desc", desc);
        return query.list();
    }
});    
}
&lt;/pre&gt;

&lt;p&gt;Listing NUS-1&lt;/p&gt;

&lt;p&gt;While this code does the job, something more readable would not only make it easier for everyone to understand, but would also cut down on time and errors.&lt;/p&gt;

&lt;p&gt;Now if we were using Java Persistence API (JPA) supported queries we could make the code in Listing NUS-1 a bit simpler as shown in Listing NUS-2.&lt;/p&gt;

&lt;pre class="brush: java;"&gt;
@PersistenceContext
EntityManager manager;

public List find(final String name, final String desc) {
    final String hqlQuery =         
        "select t from Todo t \
        where t.name = :name and t.decscription = :desc";
    return manager.createQuery(hqlQuery)
        .setParameter(&#8220;name&#8221;, name)
        .setParameter(&#8220;desc&#8221;, desc)
        .returnResultList();
}
&lt;/pre&gt;

&lt;p&gt;Listing NUS-2&lt;/p&gt;

&lt;p&gt;This is more concise and fairly readable, but several queries in a row would require repeating the same block of code many times with slight alterations and would increase our time and effort to do so. You may be asking yourself what is the problem with this? After all I am sure many of you have witten similar or even more verbose code before. The problem lies in the fact that code should be easily readable. As good developers we want to concern ourselves with the business logic, using the write tools. We shouldn&#8217;t have to spend too much of our time deciphering easy parts of the code, and queries to the database are often just that. Using GORM helps us to solve that problem, and here&#8217;s how.&lt;/p&gt;

&lt;p&gt;Let&#8217;s take what that code is doing and write it in English. The code is wanting to query the Todo table to find all by name and description. Well how do we write that out? How about this:&lt;/p&gt;

&lt;pre class="brush: java;"&gt;Todo.findAllByNameAndDesc(name, desc)&lt;/pre&gt;

That is simple, concise, and in GORM that line is actual code. This begins to show the ease of using GORM over Hibernate and we will expand on that concept when using Criteria queries later. But first, let&#8217;s see how to use GORM in our Spring application.

### Injecting GORM

The interesting thing about writing an article on Using GORM with Spring is that there is barely enough setup required to fill a blog entry, let alone an entire article. In fact, you could almost Twitter the entire extra XML needed; however, for the purpose of learning we are going to go into a bit more detail. We will show not only how to set up GORM in Spring but also various options when using Spring. This will require configuring the Spring beans, installing the right JARs, and, most importantly, understanding the various ways to use GORM in your application.

### Configuring the Spring Beans
We are going to go over in this section the necessary modifications to the spring files needed for using GORM with Spring. The modifications here will be to your bean configurations and are independent of whether you are using Spring in web environment or a standalone application. That being said of course if you were to be using Spring in a web environment no modifications are needed for the web specific files (like web.xml)
The first thing to do is to add an XML namespace to your bean configuration. This one is specifically for GORM:
xmlns:gorm="http://grails.org/schema/gorm" 

Once the namespace is set you will be able to use the GORM Session Factory instead of the Hibernate Session Factory. Listing NUS-3 is an example of the GORM bean definition that would go into your bean definition file..

&lt;pre class="brush: java;"&gt;
 &lt;gorm:sessionFactory 
     base-package="com.integrallis.demo.domain"
     data-source-ref="dataSource"
     message-source-ref="messageSource"&gt;
     &lt;property name="hibernateProperties"&gt;
        &lt;util:map&gt;
          &lt;entry key="hibernate.hbm2ddl.auto" value="update"/&gt;
      &lt;/util:map&gt;
     &lt;/property&gt; 
 &lt;/gorm:sessionFactory&gt;
&lt;/pre&gt;

&lt;p&gt;Listing NUS-3&lt;/p&gt;

&lt;p&gt;Luckily, this listing isn't too complicated. Often times with Spring beans one has to define the classes being used; however, with the use of XML namespaces that is not necessary Spring is aware based on the namespace used  With that being said Listing NUS-3 serves the same purpose as your standard Hibernate definitions usually do in Spring and that is to define the Session Factory. In fact, most of the items defined will be similar to Hibernate Session Factory listings.&lt;/p&gt;

&lt;p&gt;Line 1 is the name space reference to the GORM Session Factory, which is fairly standard stuff. The rest really is general Hibernate type configurations that are specific to GORM. Line 2 is used to specify where your domain objects exist.  Remember, with Hibernate you have to define your domain objects. There are basically two ways to do this: one is to define a directory full of hibernate XML mapping files, the other is to specify a directory of domain objects. Line 3, data-source-ref, references a data source that you have defined in Spring. This can be a Java Naming and Directory Interface (JNDI) data source, in memory data source or a more database specific data source. Line 4, message-source-ref, is specific to GORM itself. GORM allows one to define validation constraints in its domain, these constraints then print out messages via a message resource bundle. In Grails this message resource bundle is a predefined name and area, with GORM you will have to specify that item yourself. In GORM these validators are in a specific place with a specific name, but with Spring one can customize the location and name of this resource bundle. On line 5 we start to define the Hibernate properties.  If you were using Grails these items would be specified inside your DataSource.groovy file and if you were using JPA would be in the persistence.xml file.&lt;/p&gt;

&lt;h3&gt;JAR Files Needed&lt;/h3&gt;

&lt;p&gt;In addition to defining the GORM Session Factory we will also need a few of the Grails JAR files to make this work. Only three jars from Grails are needed and can be included either manually or via your Ivy/Maven configurations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;grails-bootstrap 1.1&lt;/li&gt;
&lt;li&gt;grails-gorm 1.1&lt;/li&gt;
&lt;li&gt;grails-web 1.1&lt;/li&gt;
&lt;/ul&gt;</description>
      <pubDate>Tue, 08 Sep 2009 20:36:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:9340e9fd-049e-489d-9e46-d357d7164f02</guid>
      <comments>http://www.integrallis.com/blog/2009/09/08/using-gorm-to-boost-legacy-spring-applications#comments</comments>
      <category>Java</category>
      <category>Spring</category>
      <category>Groovy</category>
      <category>Grails</category>
      <category>gorm</category>
      <category>Groovy</category>
      <category>Grails</category>
      <category>spring</category>
      <category>Java</category>
      <category>orm</category>
      <link>http://www.integrallis.com/blog/2009/09/08/using-gorm-to-boost-legacy-spring-applications</link>
    </item>
    <item>
      <title>Introducing Drools 5</title>
      <description>&lt;h2&gt;A Java Rule Engine for the rest of us&lt;/h2&gt;

&lt;p&gt;For most Java developers the idea of using a Rule Engine evokes thoughts of vendors in suits selling their bosses a complex and expensive piece of software they don&#8217;t need and the introduction of something completely foreign and intrusive to their code base. Drools 5 (http://www.jboss.org/drools/) aims to change this perception by bridging the gap between the Java developer and world of Rule-based systems.
The Quick and Dirty on Rule Engines&lt;/p&gt;

&lt;p&gt;The simplest explanation of what a rule engine is that is a very efficient pattern matcher. It matches data, referred to as &#8220;facts&#8221; against rules. Rules are simple if-then constructs that operate on the matched data. For example, imagine an example application in which the data is a loan application containing the credit score for the loan applicant. A rule could express a credit score requirement for a loan such as:&lt;/p&gt;

&lt;blockquote&gt;
    &lt;p&gt;&#8220;A loan application for ACME loans for which the loan applicant has a credit score lower than 680 will be rejected&#8221;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For the context of the this example assume that the following Java classes exist:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Mortgage: Represents a loan product belonging to a lender. It contains amongst other data, the name of the lender providing the loan.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;LoanApplication: Represents an application for a specific loan product. It contains information specific to the applicant such as the credit score and the lender associated with the application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;RejectionNotice: Represents a communication to the applicant that the application has been rejected&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;pre class="brush: java;"&gt;
rule "LowCreditScoreRejection"
dialect "java"
    when
        mortgage:Mortgage(
            lender:lenderName == "ACME"
        )
        application:LoanApplication(
            lender == mortgage.lenderName,
            score:creditScore &lt; 680
        )
    then
        application.reject("the score " + score + " is too low. \n" +
                           "A credit score of at least 680 is required");
        insert(new RejectionNotice(application));
end
&lt;/pre&gt;

&lt;p&gt;Listing SAM-1
A simple rule&lt;/p&gt;

&lt;p&gt;The rule named &#8220;LowCreditScoreRejection&#8221; is a typical Drools Rule Language (DRL) rule. It has two parts; the &#8220;when&#8221; part, also known as the &#8220;predicate&#8221;, &#8220;premise&#8221;, &#8220;condition&#8221; or simply as the &#8220;Left-hand side&#8221; (LHS for short) and the &#8220;then&#8221; part or &#8220;consequence&#8221;, &#8220;action&#8221;, &#8220;conclusion&#8221; or &#8220;Right-hand side&#8221; (RHS)&lt;/p&gt;

&lt;h3&gt;The Rule Condition&lt;/h3&gt;

&lt;p&gt;The &#8220;when&#8221; part or rule condition determines the patterns to be matched. That is, the types and characteristics of the objects that will activate the rule. In the example shown, we are looking to match two objects, an object of type Mortgage and an object of type LoanApplication. The &#8220;mortage&#8221; object must have a lenderName (mortgage.getLender) equals to &#8220;ACME&#8221; and the &#8220;application&#8221; must have a matching lender name and a creditScore (application.getCreditScore) that is less than 680.&lt;/p&gt;

&lt;p&gt;As you can see this rule only gets evaluated if there are two objects of the aforementioned types present and it is only activated if those two objects properties match the conditions in parenthesis.&lt;/p&gt;

&lt;p&gt;An observant Java developer will notice that the rule sort of looks like Java code but not quite. The when part list the classes of the objects that must be present and the values of the properties of those instances needed to activate the rule. The when part is purely a pattern matching expression using first order logic. You can think of the when part as the &#8220;where&#8221; clause in a SQL statement. Just like in a SQL statement you can create aliases for the objects being matches (and their properties). In the  &#8220;LowCreditScoreRejection&#8221; rule we have three aliases &#8220;mortgage&#8221;, &#8220;lender&#8221;, &#8220;application&#8221; and &#8220;score&#8221;. Once you have aliased a matched object that object can be used somewhere else in the rule condition and also in the rule consequence.&lt;/p&gt;

&lt;h3&gt;The Rule Consequence&lt;/h3&gt;

&lt;p&gt;We learned that the rule condition part of the rule determines what pattern of objects that will activate the rule. The &#8220;then&#8221; part or rule consequence is what happens when the conditions set forth in the &#8220;when&#8221; part are met. In Drools the consequence is simply a block of Java code. In the &#8220;LowCreditScoreRejection&#8221; rule example there are two things happening in the &#8220;then&#8221; part. First we are calling the &#8220;reject&#8221; method on the application and passing a message telling them why the application is being rejected (notice the use of the alias &#8220;score&#8221;). Next and last we are creating a new object of type RejectionNotice, passing the application object in the constructor and then passing the newly created object to the insert method. The insert method is a Drools working memory method that tells the rule engine that there is a new object that should be considered when evaluating the rules. In this case the expectation is that there will be another rule that has a condition expecting objects of type RejectionNotice and that will act upon them.
The Rule Engine&lt;/p&gt;

&lt;p&gt;From the simple example of the &#8220;LowCreditScoreRejection&#8221; rule we see that a rule engine is a system that matches facts (our data objects) against rules. The rules are then used to infer conclusions about the data. In the example, the conclusions inferred were rejection of the loan application and the creation of the rejection notice. This type of system is what is referred to as a data-driven forward chaining reasoning system. At the heart of the system is an &#8220;inference engine&#8221;; the component that does the pattern matching, activates the rules and determines how to execute the activated rules. This process is typically referred to as truth maintenance. Under the covers Drools uses a custom version of the popular Rete algorithm (see http://en.wikipedia.org/wiki/Rete_algorithm). As we can see the &#8220;forward chaining&#8221; process starts with the available facts and uses the rules to infer more facts (such as RejectionNotice) until a desired goal as been reached (determining whether a loan application is approved or rejected and communicating the rejections).
Main Drools Classes&lt;/p&gt;

&lt;p&gt;The rules like &#8220;LowCreditScoreRejection&#8221; rule are contained in DRL files (files with the extension .drl) that comply with Drools native rule language syntax. To use the created rules in a Java application you must:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;KnowledgeBuilder: A knowledge builder is the class that knows how to load and process DRL files. The impact of parsing and building in memory objects from the DRL file happens at this point. An instance of a knowledge builder can be obtained from the KnowledgeBuilderFactory using the newKnowledgeBuilder() method&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;KnowledgePackage: A knowledge package is the result of processing a DRL file; a serializable object. The knowledge builder has a getKnowledgePackages() that returns a collection of knowledge packages.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;KnowledgeBase: A knowledge base is where the knowledge packages are deployed to so that they can be used at runtime. The knowledge base is the object that will be used to create knowledge sessions. This knowledge base is a thread safe construct that serves as a factory of sessions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;KnowledgeSession: The knowledge session is the object used to interact with the rule engine. It is throught a session that you will make the rule engine aware of the facts (the data) that the rule engine will evaluate against the available rules.
Inside the Rule Engine&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Inside the rule engine, after you have inserted your facts into a knowledge session and invoked the session fireAllRules() method:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Rules are matched against the facts in the knowledge session using the pattern matcher (Rete algorithm)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The unordered list of activations (the Rules that apply based on the facts) is ordered internally (by a conflict resolver) in the session&#8217;s agenda&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The first Rule in the agenda is the executed, possibly triggering steps 1 and 2 again&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This loop is how a Rule Engine infers knowledge from existing facts using rules. You can see that a Rule Engine using pattern matching to reduce/transform the problem space to arrive at a set of facts that can be considered a solution to the problem at hand.
Getting Started with Drools 5: Classifying you Twitter network&lt;/p&gt;

&lt;p&gt;Rule Engine development introduces enough conceptual complexity (mainly inherited from the A.I. lingo and academia) that feels fairly unapproachable us Java developers. So, let tackle a simple but yet representative problem using Drools 5.&lt;/p&gt;</description>
      <pubDate>Wed, 19 Aug 2009 19:03:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:94406f97-7631-4cb6-8d02-0f317cd82424</guid>
      <comments>http://www.integrallis.com/blog/2009/08/19/introducing-drools-5#comments</comments>
      <category>Java</category>
      <category>JBoss</category>
      <category>drools</category>
      <link>http://www.integrallis.com/blog/2009/08/19/introducing-drools-5</link>
    </item>
  </channel>
</rss>
