Thursday, December 10, 2009

Hazelcast Groovyness

Data distribution is a pretty cool topic. Recently, I have been working with Hazelcast, which is an open source clustering and data distribution platform for Java. Well, I really like what I have seen so far and I figured why not have some fun with Hazelcast and Groovy.

I started by adding the Hazelcast 1.7.1 jar to $GROOVY_HOME/lib. Hazelcast, at an introductory level, provides distributed implementations of java.util { Queue, List, Set, Map }. I can run a Groovy script on multiple JVM's and I can share a Map of customers on each instance. For example:

    def customersMap = Hazelcast.getMap("customers")

Now, I have an instance of Map and I can add values using Hazelcast's distributed id generator:

def idGen = Hazelcast.getIdGenerator("customer-ids")
def id = idGen.newId()
customersMap.put(id, "Customer $id")

So, that was pretty simple, right? Here is the entire Groovy script HazelcastGroovynessAdd.groovy:

import com.hazelcast.core.Hazelcast
import com.hazelcast.core.IdGenerator

def customersMap = Hazelcast.getMap("customers")
def idGen = Hazelcast.getIdGenerator("customer-ids")
def id = idGen.newId()
customersMap.put(id, "Customer $id")


I can open up a few different command prompts and enter:

> groovy HazelcastGroovynessAdd.groovy

Now, the customers Map has a few customers in it and our Groovy scripts are still running. Let's add an com.hazelcast.core.EntryListener to the customers Map so we can detect a com.hazelcast.core.EntryEvent. Here is HazelcastGroovyness.groovy:

import com.hazelcast.core.Hazelcast
import com.hazelcast.core.EntryListener
import com.hazelcast.core.EntryEvent

def listener = [
    entryAdded: { EntryEvent ev ->
        println "key $ev.key was added with value $ev.value to $ev.name"
        Hazelcast.getMap("customers").values().each {
            println it
        }
    },
    entryUpdated: { EntryEvent ev -> },
    entryRemoved: { EntryEvent ev -> },
    entryEvicted: { EntryEvent ev -> }
] as EntryListener

def customersMap = Hazelcast.getMap("customers")
customersMap.addEntryListener(listener, true)

In the above code, we define listener which implements com.hazelcast.core.EntryListener. I now start up HazelcastGroovyness.groovy at a new command prompt(s):

> groovy HazelcastGroovyness.groovy

We can go back to our original HazelcastGroovynessAdd.groovy script and open (re-open) a few more command prompts and run the script that adds customers to the Map. Now in each running instance of HazelcastGroovyness.groovy we see something like:

key 2000001 was added with value Customer 2000001 to c:customers
Customer 2000001
Customer 1000001
Customer 1

Hazelcast is very cool, easy to use technology that provides distributed data with a few lines of code, especially with Groovy. More information can be found at Hazelcast's website and at the project site at Google Code.

Tuesday, November 03, 2009

Grails on JBoss AS 5.1.0 GA

Grails is changing the way Java developers approach Web development. If you are not familiar with Grails, it is a Web application platform for the agile and dynamic language, Groovy, that runs on the Java Virtual Machine. There are plenty of available books on Groovy and Grails and there is a plethora of blog posts and online documentation to help you get started with your first Groovy and Grails project. This article will discuss creating a simple Grails application for JBoss AS 5.1.0 GA and demonstrate how simple Java Web development can be.


I have taken some time to explore developing a simple Grails 1.2-M3 application and deploying it on JBoss AS 5.1.0GA. Grails is all about productivity. In a few short steps, I create a simple Web application, generate a Web archive (.war) file and deploy it on JBoss AS 5.1.0 GA.

After Grails 1.2-M3 is installed and properly setup, I open a command prompt and enter

> grails create-app


and when I am prompted, I enter a name for my application.

> demo


A directory is created with the same name as my application. I then navigate to that directory.

> cd demo


Next, I create two domain classes to represent the solution to my business problem, storing company information in a database.

> grails create-domain-class org.axiomaticit.model.Company
> grails create-domain-class org.axiomaticit.model.Address

The above commands create two .groovy files in the directory grails-app/domain/org/axiomaticit/model/, Company and Address. Here is what the Company.groovy file looks like:

package org.axiomaticit.model

class Company {
    static constraints = {

    }
}

Next I open the Company.groovy and Address.groovy files in a text editor or IDE and add some detail. Here is the Company.groovy file after I add some fields and constraints:

package org.axiomaticit.model

class Company {

    String name
    String website

    static hasOne = [address:Address]

    static constraints = {
        name(blank:false)
        website(blank:false, url:true)
        address(nullable:true)
    }

    String toString() {
        "$name"
    }
}

And here is the Address.groovy file:

package org.axiomaticit.model

class Address {

    Company company
    String street1
    String street2
    String city
    String state
    String postalCode

    static constraints = {
        company(nullable:false)
        street1(blank:false)
        street2(blank:true)
        city(blank:false)
        state(blank:false)
        postalCode(blank:false)
    }

    String toString() {
        "$street1 $city, $state"
    }
}

If you are not familiar with Groovy and the conventions of Grails, this might be a little weird to look at. If you are a Java developer, some of the above code looks a lot like what you already know, right? Let's talk about what I just did. I created two classes to represent company information. First, I created a company class with a few important fields like 'name' and 'website'.

String name
String website

Then I created another class, Address, to represent standard US address data.

String street1
String street2
String city
String state
String postalCode

I also added an Address to the Company class,

static hasOne = [address:Address]

and a Company to the Address class.

Company company

Don't get too wrapped up in all the details if you are new to Grails, but what you should understand is that I am building a domain model and creating properties and relationships between persistent entities. The Grails documentation is quite detailed and the user community is also very helpful if you get stuck with the Grails conventions and semantics of Groovy.

Now that I have my domain model, I want to create the controllers and views for my Web application. Controllers and views? Think MVC (Model, View, Controller). So, I go back to my command prompt and enter each command:

> grails generate-all org.axiomaticit.model.Company

> grails generate-all org.axiomaticit.model.Address

The commands above will create a few things based the domain model objects; they create default controllers and views that will support basic CRUD (Create, Read, Update, Delete) functionality. The controllers will be in grails-app/controllers/org/axiomaticit/model/ and the views will exist in grails-app/views/company and grails-app/views/address respectively for each domain model object Company and Address. Let's go ahead and see what I have created and run the application from the command line.

> grails run-app

Once the application starts up, I browse to http://127.0.0.1:8080/demo and test out the application. It might not be everything I wanted, but I have a great starting point, right? Let's deploy this on JBoss AS 5.1.0 GA. Back to the command line to create a Web archive (.war) file.

> grails war

If everything builds properly, I have just created a file, demo-0.1.war, that I can drop into the JBoss deploy directory. I can start up JBoss and point the browser at http://127.0.0.1/demo-0.1 and test out the application. Wow, that took about 10-20 minutes and now I have a fully-functional Web application. Grails is a great platform for proof-of-concept work but because it is based on proven technologies like Spring and Hibernate, many developers are moving Grails applications right into production. Combine Grails with an enterprise level application server like JBoss AS 5.1.0 and you have productivity built on top of dependability.

This is a copy of what I posted at Jboss.org.

Tuesday, October 06, 2009

Spring 2.5 Aspect Oriented Programming

Spring 2.5 Aspect Oriented Programming

I have finally finished reading Spring 2.5 Aspect Oriented Programming by Massimiliano Dessì. PACKT Publishing sent a copy of this book to me many weeks ago and I finally found enough time to finish reading the book this weekend. This book is a great resource for anyone looking for a very detailed look into Spring 2.5's Aspect Oriented Programming support. There are plenty of real world examples and code snippets that make understanding the topic easier for mid to senior level Java developers who are already familiar with the Spring Framework and its conventions. The author not only addresses the "how-to" questions, but he also spends time answering the "why" questions. This is very important because many people have an understanding of Aspect Oriented programming, but struggle to find valid cases where it fits into a project.

Chapter 1, Understanding AOP Concepts, discusses code tangling or coupling, AOP inside the IoC container and configuration.

Chapter 2, Spring AOP Components, addresses the key Spring components; Aspects, Pointcuts, Advice, Joinpoints and Advisors.

Chapter 3, Spring AOP Proxies, takes a look into how AOP is possible with Spring. This chapter discusses how AOP is realized and how crosscutting is possible within a Spring project.

Chapter 4, AspectJ Support, takes a look at how Java 5 and AspectJ's annotation support makes AOP even easier.

Chapter 5, Design with AOP, looks into common design decisions for concurrency, caching and security that involves AOP solutions.

Chapter 6, Three-tier Spring Application, Domain Driven Design, sets up chapter 7 with a sample DDD application.

Chapter 7, Three-tier Spring Application, Tests and AOP, dives into how AOP fits into the development of the example created in chapter 6.

Chapter 8, Develop with AOP Tools, puts together the rest of the pieces; the IDE, application server and database to come full circle. So, not only do you learn the technology, but at the end you have a real world example of AOP in practice.

Overall, Spring 2.5 Aspect Oriented Programming is great book that takes a detailed look at Spring 2.5's AOP support.

Monday, August 31, 2009

Ruby Proc Fun

I am fairly new to Ruby but I do have experience with Groovy so I have found learning and experimenting with Ruby somewhat of an easy effort. The Ruby community is pretty big so there are plenty of blog posts and other Web sites that are available, via a Google search, to help understand some problems when I get stuck. I started playing around with Ruby Proc (procedures), if/elsif/else and case/switch statements and here is what I am having fun with:

# define our apple Proc
apple = proc { |t| puts "my apple" + t }

Above we have our executable (proc) code assigned to the 'apple' variable.

# doIt1 with if statements
def doIt1(c, t)
  if t.respond_to?("call")
    puts "-- callable"
    c.call " is awesome"
    t.call " is really awesome"
  elsif t.kind_of?(Array)
    puts "-- not callable Array"
    t.each { |t1| c.call t1 }
  else
    puts "-- not callable String"
    c.call t
  end
end

Then we have a method 'doIt1(c,t)'. This method expects 2 arguments; the first argument, 'c', I expect is a Proc and the second argument, 't', I expect to be a Proc, Array or String.

if t.respond_to?("call")

The 'if' statement checks to see if 't' has a method named 'call' that it will respond to. I think the 'respond_to' method is great for dynamic languages. I could have just checked to see if 't' is a Proc as well, but then that limits me to one Object type, right?

t.kind_of?(Array)

The 'elsif' statement checks to see if 't' is of type Array. Like instanceof in Java.

# doIt2 with case/switch block
def doIt2(c, t)
  case t
    when Proc
      puts "-- callable"
      c.call " is awesome"
      t.call " is really awesome"
    when Array
      puts "-- not callable Array"
      t.each { |t1| c.call t1 }
    when String
      puts "-- not callable String"
      c.call t
    else
      puts "not valid"
    end
end

Then I created a method just like 'doIt1' called 'doIt2'. In 'doIt2', I used a case/switch statement and handled things similarly to 'doIt1'. In the second method, I check 't' to be of type String and have a default case for when 't' is not a Proc, Array or String.

# doIt1 tests
doIt1 apple, apple
doIt1 apple, " works good"
doIt1 apple, " works hard"
doIt1 apple, [" looks good", " looks elagant", " looks shiny"]

# *'s used to separate method tests
puts "*" * 40
puts "*" * 40

# doIt2 tests
doIt2 apple, apple
doIt2 apple, " works good"
doIt2 apple, " works hard"
doIt2 apple, [" looks good", " looks elagant", " looks shiny"]

Then I wrote a few 'tests' to see what would happen. Ruby is fun and I definitely enjoy working with Ruby and Groovy. Here is the full script file: appleProc.rb

Sunday, June 21, 2009

Spring Web Flow 2 Web Development



Spring Web Flow 2 Web Development is a great read for developers who want to take a hands-on approach to learning a great technology. By following and working with the examples, you can experience the basic principles of Spring Web Flow 2 and how it integrates with JSF, Spring Security and AJAX. This book is great for Java developers who are already using the core Spring Framework and now want to involve Spring in the presentation tier of a Web application.

Within the first few chapters, the authors present a good overview of Spring Web Flow 2. Chapter 2 starts with the installation of Spring Web Flow 2 and some help with running the examples packaged within the distribution. Chapter 2 also goes over putting together a development environment that is based on some pretty standard open source technologies like Ant, Maven, Ivy, Eclipse (Spring IDE) and NetBeans. The "Support for Developers" section of chapter 2 is a great feature of this book because if you are not already familiar with the aforementioned technologies, you get exposure to some great open source development tools. After learning a little more about how everything works together, the authors throw in a little JPA and by the end of chapter 2, you have completed your first example.

The focus of chapter 4 is Spring Faces. In my opinion, if you are going to work with JSF, focus on this chapter because Web Flow 2 is what is missing from JSF. I am not a big fan of some of the JSF implementations I have used in the past, but Web Flow 2 makes working with JSF and Facelets a bit nicer and the Spring Faces tag library is very helpful. Combine chapter 4 with chapter 5's sections on Subflows and AJAX and you will have a good foundation for creating rich Web applications with Web Flow 2.

Chapter 6 illustrates Spring Web Flow 2's testing support. A very important part of the development process is testing. Too many developers overlook the importance of testing especially when it comes to Web applications. Web Flow 2 comes with great testing support and as the book points out, testing support is part of the framework rather than an after-thought for developers.

Some Web applications require some level of security and most enterprise Web applications have to incorporate support for authentication and multiple levels of authorization. Chapter 7 discusses the integration of Web Flow 2 with Spring Security, formerly Acegi Security. This chapter provides a great high level view of Spring Security configuration and how to lock down access to parts of a Web page and even method level security.

Overall I enjoyed reading this book and learning Spring Web Flow 2. The authors, Markus Stäuble and Sven Lüppken, did a great job in presenting the core concepts of the technology in only 200+ pages. Prior to reading the book, I had little knowledge of the technology, but now I would be comfortable working on a project that is utilizing Spring Web Flow 2. More information about the book and authors can be found at www.packtpub.com.

Monday, May 11, 2009

Groovy Prime Numbers

The other day I wanted to prove the power of Groovy to a few more core Java developers. I sat down and played with a little script that I think proves the power, or ease of use, of Groovy while having fun with number theory. My goal was to have a Collection that contains Prime Numbers calculated from a given range of numbers x to y, or in Groovy syntax x..y. I am taking a few things for granted with this script. For example, I know that 2 is the lowest Prime Number (it helps simplify the algorithm) and that 1 is not a Prime Number. So here's the script:

def t = 1..100
def v = []

t.each { n ->
    (2..n).each { d ->
        if(n % d == 0 && n != d)
        v.add(n)
    }
}

println t - v - 1

We have our range of numbers t and we are capturing the non-Prime numbers and adding them to our Collection v. The final line of the script is doing a lot of groovy work for us that would take a few more lines of code with plain Java syntax. What is it doing for us? It is taking our range of numbers t and subtracting (removing) our non-Prime numbers collected in v. This line is also removing the number 1 because we know that 1 is not a Prime Number. Finally, it is printing the result like so:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Very cool stuff. Now, I know that many of us are rarely building a Collection of Prime Numbers and I know this script does not do things in a timely manner with a range like 1..10000 (it took a couple of minutes), but I am sure this feature of Collections in Groovy can be utilized in many ways in my development.

Monday, February 09, 2009

Groovy Closure Currying

So I have been diving into Groovy a bit heavier lately and I was just checking out Closure currying. So let's say I have a Closure, like myClosure below, that takes in 2 parameters, var1 and var2. Let's look at the code:

...
def myClosure = { var1, var2 ->
    var1.call()
    var2.call()
}

def walk = { println "I am walking..." }
def run = { println "I am running..." }
def fly = { println "I am flying..." }

myClosure(walk, run)
myClosure(walk, fly)

def walkFirst = myClosure.curry(walk)
walkFirst(run)
walkFirst(fly)
...

When I call myClosure(walk, run) and myClosure(walk, fly) I get:

...
I am walking...
I am running...
I am walking...
I am flying...
...


Well what curry() does for us is take out some of the duplication that we may find when passing in parameters to our Closure. I notice that the Closure walk is passed in both times because we want to walk before we can run or fly. If we take advantage of curry() we can create another Closure called walkFirst. The Closure, walkFirst, is created here:

...
def walkFirst = myClosure.curry(walk)
...


This now gives us a simpler Closure we can send run and fly into without worrying about having to pass in walk first. This is a very useful utility of Groovy and Closures and we get exactly what we were expecting:

...
I am walking...
I am running...
I am walking...
I am flying...
...


Very cool stuff. Do yourself a favor, read more about Groovy.

Sunday, February 08, 2009

Adobe Air: Getting Started

I wanted to create this post because I needed a reference to where I am at with Adobe Air/Flex. Plus Vladimir Vivien said I needed to blog about what I have been doing. So here is what I have been doing:

I have mostly been creating Flex form based applications with datagrids that rely on RESTful Web services mostly running on Groovy/Grails but I have also created an Air application that communicates with TIBCO EMS. I want to go over the TIBCO integrated Air app, I call systemStatus. Basically, systemStatus makes an HTTP request to a URL like http://host:port/systemStatus and a TIBCO HTTP Receiver listens and responds after executing some processes on the ESB. The TIBCO project includes processes that execute some simple tasks, like queries on databases, and the results are accumulated and mapped to a pre-defined schema. The response is an XML document that looks something like this:

...
<resources>
    <resource>
        <name>Production Oracle</name>
        <type>database</type>
        <vendor>Oracle</vendor>
        <status>offline</status>
        <instance>server 1</instance>
    </resource>
.
.
.
</resources>
...


The XML is pretty simple, but it does what I need it to do. It basically gives us some META data and a status for each of the resources, like databases, which are dependencies of the deployed TIBCO projects. I am going to stay away from the details pertaining to the TIBCO application but if you need some help setting up something like this, just contact me.

Next we turn to the Air/Flex application. The Air application is made up of only a few major components: <mx:HTTPService>, <mx:Panel>, <mx:TextInput>, <mx:DataGrid> and <mx:Button>. At the simplest level, the <mx:HTTPService> makes the call to the TIBCO service and the <mx:DataGrid> handles and displays the XML results. I have added the <mx:TextInput> component so the app can be configured to point to different TIBCO environments running the deployed systemStatus TIBCO application that provides the XML results. Here is the meat of the Air application:

...
<mx:HTTPService id="systemStatusService" result="r_Handler(event)" resultFormat="e4x" fault="f_Handler(event)" url="http://{serverName}" />

<mx:Panel title="systemStatus" height="100%" width="100%" paddingTop="10" paddingLeft="10" paddingRight="10">

<mx:ControlBar horizontalAlign="left">
<mx:Label text="Server:Port"/>
<mx:TextInput id="serverNameInput" enter="setServerName()"/>
</mx:ControlBar>

<mx:Label text="Systems:"/>

<mx:DataGrid id="systemDG" width="100%" height="80%"
dataProvider="{systemStatusService.lastResult.resource}"
editable="true">
<mx:columns>
<mx:DataGridColumn dataField="vendor" headerText="Vendor" editable="false"/>
<mx:DataGridColumn dataField="name" headerText="Name" editable="false"/>
<mx:DataGridColumn dataField="instance" headerText="Instance" editable="false"/>
<mx:DataGridColumn dataField="type" headerText="Type" editable="false"/>
<mx:DataGridColumn dataField="status" headerText="Status" editable="false"/>
</mx:columns>
</mx:DataGrid>

<mx:ControlBar horizontalAlign="left">
<mx:Button id="refresh"
label="Refresh"
rollOver="refresh_rollOver(event);"
rollOut="refresh_rollOut(event);"
click="refresh_clickHandler();"/>
</mx:ControlBar>

</mx:Panel>
...


Here is a screen shot of the Air application:



The refresh button will initiate another request to the TIBCO service and if anything has changed, the XML results will reflect the changes and the <mx:DataGrid> will be updated.

This is a pretty simple idea, but it demonstrates how we can take one technology and combine it with other tools and technologies to create useful applications to make life easier.

Download the code:
systemStatus.zip