Thursday, August 20, 2009

Choking on Java

As you can tell from my blog I am a long time Java developer who likes to flirt with dynamic languages. Not surprisingly my two favorite languages at this point are Groovy and Ruby. Therefore, I enjoy working with the Grails and Rails frameworks. After working with Java for so long I was starting to get tunnel vision around a single language. After all, Java is a general-purpose language that can do anything if you bend it enough.

However, Java is not always the best solution for all situations. Obviously, Web development is one of those glaring areas where Java can work but might not be the best candidate. I began developing web applications with Java using plain old servlets and jsp pages. Like most Java developers I also discovered Struts 1. While some of the components of the framework seemed a little strange, Struts was better than my homegrown attempt. So I developed with Struts for a while but I was not entirely satisfied. Of course there were other issues to tackle outside of the presentation layer including persistence, transaction handling, and other services. So I evaluated JDO, EJB, and Hibernate. I finally settled on Hibernate but there was still a mess between my presentation tier and my persistence layer. Later I found Spring and glued everything together. After evaluating countless presentation frameworks I refined my Java Web stack over time using Stripes, Spring, and Hibernate. This combination took a lot of experimentation but I was able to make Java conform to the web in a relatively lightweight manner. The point is that I had to do a lot of bending here.

When Rails first came on the scene I was fairly closed minded mainly because of my investment in Java. How could this newcomer trump all my hard work or be as robust as Java? Well after taking Rails out for a test drive I quickly realized how over-architected Web development was with Java. It reminded me of so many early math classes where it would take several pages of computation to achieve a result. Then more advanced math classes introduced techniques to achieve the same results in just a few steps. I appreciated the simplicity of solving a problem with less computation and yielding the same results (or better). Doing less work for the same results once I understand the underlying theory works for me.

But with RoR there was a fair bit of voodoo so I became less intrigued by Rails and wanted to know as much as possible about Ruby. Ruby turned out to be a fun language with constructs that are currently not available or easy to achieve with Java (i.e. closures, better mixin techniques, creating your own DSLs with builders, everything is an object, etc). I quickly realized that I could code much more expressively and achieve the same functionality with a lot less lines of code. Testing my code with a dynamic language instead of Java was also enjoyable because it was simpler. I actually wanted to do testing! Exposure to a new language like Ruby actually improved my Java code (and made me resent how noisy Java is). So now I am an aspiring polyglot with an open mind to new languages.

Not long after I looked at Rails I saw that Grails 0.3 was available (I think I first saw it on http://java.net). So the Java camp was attempting to answer Rails with Grails. OK fine, I took a look at Grails and this is when I was first exposed to Groovy. Groovy offered much of the same dynamic capabilities as Ruby and worked well with my existing Java code (mostly). And Grails offered much of the same convention over configuration principles like Rails. Even better I could integrate my Grails application with my existing Java code. It was like winning the World Series of Poker when I hooked up my existing Spring beans and Hibernate annotated domain objects with Grails. Grails automatically recognized my Spring beans and seamlessly added all of the GORM dynamic methods to my domain classes.

However, I still liked the Ruby language slightly better than Groovy because it did not carry the Java baggage along with it. So now I have a language and a framework that are great for new development, but I could not reach out to my existing Java classes or external libraries with Ruby. Then I found JRuby. JRuby allows me to write Ruby code and integrate with my Java code, Spring beans, etc. However, if I was going to use Rails and wanted to follow their paint by numbers framework then I was stuck with ActiveRecord. Also Rails does not have a service layer concept so my Spring beans did not naturally fit in the Rails framework. I quickly found out how to create a Spring bean factory in JRuby so my Rails controllers could access these services.

As much as I like JRuby there are some things that I want. First, I would like to see JRuby continue to strive for near Java performance. I do realize that we are talking about a dynamic language but I believe that this can be achieved. Second, I think that JRuby needs to provide easier integration for popular open source frameworks like Spring and Hibernate. Why shouldn’t JRuby/Rails emulate Grails the same way that Grails “borrowed” from Rails. Maybe the JRuby team could offer these items as gems to supplement the Rails framework. Or maybe this will be a pluggable feature with Rails 3? This is about bridging the gap between the Java and Ruby communities. Finally, I want to see Engine Yard offer commercial support and training for JRuby (which seem inevitable now that Charles Nutter is at EY).

While building Rails applications is fun, deployment can be a pain. I think that the leveraging JRuby/Rails on a Java platform makes a lot of sense here. Ruby contains several gems for integrating your Rails application in a Java environment. First, there is the Warbler gem, which allows you to take your Rails application and package it up in a standard war file format. So now your Rails application can be deployed on any standard Java container. Second, there is a Glassfish gem for deploying your applications without Warbler. The JDBC-ActiveRecord gem allows you to use your JDBC drivers to connect to your database instead of the Rails drivers. By deploying your Rails application on a JVM you get extra benefits like simpler deployment strategies, better threading support, and easier ways to scale. So while you might want Rails for development, the JVM might offer better services for housing your application. Even if you don't have to integrate any Java code you should still consider JRuby for Rails development IMHO.

So, if you choose to use a dynamic language should you use Grails or Rails for Web development? I do not think there is a cut and dry answer to this question. In this case, the lines are a little blurry because the underlying languages seem to be converging in capabilities. However, I will provide my 2 cents on this issue and watch the comments for this entry fill up. Let me start off by saying that I like both frameworks for different reasons.

Let's start with Grails. Grails is great for Java developers that have existing experience with Spring and Hibernate. The migration to Grails will benefit these people the most because they understand how Spring and Hibernate work. Grails is pretty much just a wrapper around these frameworks so when problems arise they will have the same issues that had to be solved before. The benefit is that this is a great way to get started with a dynamic language (like Groovy) and start to understand what all the fuss is about using a familiar set of tools. Plus, as I indicated earlier you could drop in your Spring beans and Hibernate classes and watch them work out of the box. You will need a deep understanding of Spring and Hibernate when things go wrong to troubleshoot problems as they arise. This is where things might break down for developers that do not understand these frameworks.

Now let's talk about Ruby on Rails with JRuby. Working in Rails is just a fun way to develop. Rails was created solely to solve the domain specific problem around web development. And Rails developers seem to introduce easy solutions to mundane problems. There are lots of plugins and gems that can make Rails even more enjoyable. However, there are thousands of Java libraries available that you might want or need to integrate with. As a Rails developer why wouldn't you at least give yourself the option to tap into those libraries?

So how does everybody win? I believe that everyone will benefit if these two communities come together. I have observed the Java and Ruby communities for some time and seen a lot of mud thrown from both sides. At the end of the day you have to ask yourself why these two groups cannot see that they really need each other at some level. Is this more of a cultural gap than a technical one? Java is infused into so many organizations and is not likely to go away any time soon. What better way to get your Rails application deployed in a Java shop than making a case with JRuby? Also, if you want to evangelize and strengthen Rails as a popular development platform why not build on top of one of the largest existing infrastructures? Rails will only survive by gaining acceptance as a viable framework.

As for Java developers that think that Rails is not a good solution for Web development I say they are passing judgment without entertaining the idea. Let's face it, Java is legacy. If you still think that JSF provides rapid development or think WebSphere is a great application server then you probably will not buy into this blog entry. As technologists we need to find and accept better ways to solve problems. Maybe Rails is not the end all solution for Web development. There are many emerging frameworks like Seaside, Django, Lift, Sinatra, Camping and more that believe they have a better mousetrap. This is a sign that people believe that Java is too complicated and over-architected for web development.

Let me summarize by overstating how much Web development has changed. Java developers and Ruby developers need to understand how the JVM can benefit them. Web development using domain specific languages and dynamic languages are hot and over architected Java solutions are not. But there is a middle ground and whether you choose Grails, RoR, or some other framework to simplify your web development you are probably on the right track. Finally, both the Java community and the Ruby community have things to offer each other to secure their survival.

Well off to look at more Scala...

Wednesday, July 1, 2009

IntelliJ 8.1 buuild 9732 hangs with Apple Java for OS X 10.5 - Update 4

If you are a Mac user and you applied Apple's Java for OSX 10.5 Update 4 you might be experiencing crashes with IntelliJ 8.1.x. It appears that the software was not tested well enough against the developer preview before the update went GA. You can read more about this here:

http://lists.apple.com/archives/java-dev/2009/Jun/msg00142.html

While you cannot rollback the Java update on the Mac there is a workaround for this issue as described here:

http://www.jetbrains.net/devnet/message/5240216

Here are the steps I used to correct this on my Mac:

Rename this file:

/Applications/IntelliJ IDEA 8.1.3.app/Contents/MacOS/idea

Replace the idea file with the Java system file like this:

cp /System/Library/Frameworks/JavaVM.framework/Resources/MacOS/JavaApplicationStub 64 to /Applications/IntelliJ IDEA 8.1.3.app/Contents/MacOS/

This did correct the issue for me and the software has been stable. IntelliJ was not the only software affected by this update. I also had to get a new version of DbVisualizer (6.5.7) to correct issues with that software as well because of this issue.

Tuesday, June 2, 2009

RSpec and AutoSpec with JRuby

I had a little bit of a struggle last weekend setting up RSpec with JRuby so I thought I would share the way I set this up. I am not sure why I could not find more information on how to do this so I thought I could help the next guy. Anyways, I am using JRuby 1.3.0RC2 which comes bundled with RSpec 1.2.6 which is great but there were two issues I needed to address before using this in my Rails application.

The first issue was introducing RSpec into my Rails application. It turns out that this is simple. First you need to install the RSpec-Rails gem like this:

jruby -S gem install rpec-rails

Next switch to your Rails project home directory and scaffold out the RSpec components like this:

jruby -S script/generate rspec

This will introduce an rspec folder with the initial scaffolding you will need to write RSpec tests for your Rails application. This only needs to be done once.

The next thing I wanted to do was use AutoTest so that my tests would run in the background while I am coding. This way I can make changes to my code and tests and have the modified tests run on a continuous basis. When we ran the RSpec scaffolding in the Rails application we received an autospec script in the script folder. This is what will allow you to have this perform your local continuous testing. The only other gem you will need is the ZenTest gem which is used for AutoTest and AutoSpec.

jruby -S gem install ZenTest

You are now setup to run all of your Rails RSpec tests manually with Rake from your project home directory:

jruby -S rake spec

Or you can turn on AutoSpec and let this happen in a Terminal like this:

jruby -S script/autospec

I am also using the latest NetBeans IDE (6.7 RC1) for development and find that AutoSpec works great there as well. To do this right click on your project folder and click AutoSpec. This will kick off the script. Here is an example of some of my results:




NetBean also has a nice navigator window for seeing an outline of your specs:


I think that RSpec and AutoSpec provides a very easy and productive way to practice TDD in your Rails applications. Well back to writing more tests...

Friday, March 27, 2009

I Code Better Without A Computer

Alright so this might sound a little silly because we need a computer to actually write code. However, I find that most of my best design, code, and refactoring efforts happen when I am not at a computer. This has been a common theme for me since college where I would wake up with a thought about some problem I was working on but could not resolve while conscious. I would literally wake up some nights with an answer to something that I obsessed about during the day.

I continue to find myself doing the same thing with my code. This happens when I am driving, sleeping, watching TV, playing WoW, showering (don't think too hard on that one) or while my wife is trying to carry on an important conversation (bad idea BTW). I just tell her that I was listening but spawned a new thread while she was talking. This tends to not work in my best interest so don't try that one. I will let you know when I think of a response that won't get you in trouble.

I guess I found out that I was not the only person who experiences this behavior when I attended Neal Ford's On the Lam from the Furniture Police presentation. There he explained how the right and left sides of your brain operate and how they contend for time. The right side of your brain is where your creative non-linear thoughts occur while the left side of you brain spends it's time with rational linear thought processes. It turns out that if you can occupy the left side of your brain with mundane white noise like sleeping, driving, showering, WoW, the wife, whatever...you free up time for your right brain to produce meaningful analytical abstractions without your left brain interfering.

How many times have you resolved an issue while you are in the process of explaining it to a coworker. Your own blabbering can shut down your right brain so your left brain can reason things out! Here is another cool technique that Neal Ford suggested which sounded bizarre at first to me but then made good sense (to me at least). He suggested putting a rubber duck on top of your monitor and when you get stuck you explain the issue to the duck. This is not a magic duck (I don't think). The point is you are freeing up your right brain to perform the tasks you are really interested in.

I am pretty interested in understanding more about how the brain functions and will probably read Andy Hunt's book Pragmatic Thinking and Learning: Refactor Your Wetware. Maybe if I can control my mind I might be able to control my code. Those of you that know me might agree...

Swiz is the Shiz

Now that I am doing more Flex development I am back to researching MVC frameworks for the Flex client. I initially did what most Flex developers do as they start learning and create inline code that cannot be maintained. From there I went to the other side of the spectrum and tried Cairngorm which did exactly what it said it would do but at the price of being very heavy but keep your code organized. The biggest problem with Cairngorm is that it lead to code explosion with all of the objects it required you to create. Needless to say I wanted to find something simpler.

I then researched some other available frameworks like PureMVC and Mate. PureMVC looks like and octopus of classes and seems like a Cairngorm like framework with incremental improvements. Mate was a lot closer to what I wanted but seemed to introduce too much custom framework.

Finally, I found Chris Scott's Swiz framework. Swiz works that way I think since I do so much Spring development in Java. Swiz's main goal is reduce the clutter you maintain in Flex like singletons and service locators by using dependency injection of your components in your application. Swiz also comes with a very intuitive annotation model for dynamically dispatching and registering event listeners to your methods. All of the nonsense you would normally write with some of the other frameworks are abstracted in Swiz and you end up with little framework noise. Visit the Swiz site and look at the docs. You will be up and running in about an hour if you understand how dependency injection works already. You can also check out Christope Coenraets Swiz example for a simple running example. Also look at the Flex 360 video from Chris Scott for a full explaination about this framework.

Tuesday, February 24, 2009

Mockups

I found this cool little mockup tool that is very easy to work with called Balsamiq. I generally use OmniGraffle for sketching mockups and wire frames but I found this tool to be very enjoyable to work with. When you DnD you elements to the screen you get lots of options for editing that is very intuitive. Here is a quick example of something I whipped up with this tool so you can see what you can do in 2 minutes. The images are cartoonish but I think it will resonate well with end-users when doing design meetings or technical presentations. Simple! Easy to use! Great tool!

Monday, February 16, 2009

Hudson, run a bypass

I thought I would share a pleasant experience I had with a CI (continuous integration) tool called Hudson. I have used other tools like this in the past including Anthill, CruiseControl, and TeamCity. While these tools did their job none of them seemed as easy to use as Hudson.

Hudson downloads as a self contained war file that launches from a command line:

java -jar hudson.war

That is really it to get running and there is nothing else to install. Hudson comes with a built in servlet engine called Winstone. There are no configuration files that you have to touch because you use the built-in intuitive UI to configure the Hudson server and your projects. There are tons of plugins available that can be used to extend the core functionality or you can write your own custom plugins. We run Starteam (yuck) for source control internally but I found a plugin for it and installed it from the web administration. Very simple! I was able to configure SCM checkout, setup email notifications, and execute our build script successfully in about 15 minutes without knowing the product. If you want to see what awesome open source projects look like check out Hudson.

Sunday, February 1, 2009

Flex 3 Builder on Mac OSX

I ran into problems installing the Flex 3 Builder Professional edition on my Mac. This was because my current version of Java was set to 1.6.0. Before you install make sure you go in your Java Preferences (from spotlight) and make sure your Java application setting is J2SE 5.0 32 Bit by dragging it to the top of the list (temporarily). Then install Flex Builder 3 from the DMG file. You will not encounter any errors in the installation.

Finally, I needed to use the latest version of Java but Flex Builder still needs to run on the 1.5 JDK. For this I went through Finder to edit

/Applications/Adobe Flex Builder3/Flex Builder.app/Contents/MacOS/FlexBuilder.ini

From here just add these lines to the top of this file so you can use the right version of Java:

-vm
/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0

-vmargs
-Xdock:icon=../Resources/flexbuilder.icns
-Xdock:name=Flex Builder
-XstartOnFirstThread
-Xms128m
-Xmx512m
-XX:MaxPermSize=256m
-XX:PermSize=64m
-Dorg.eclipse.swt.internal.carbon.smallFonts
-Dorg.eclipse.swt.internal.carbon.noFocusRing

Now when Flex Builder starts it will use the right version of Java. Go back into Java Preferences and move Java SE 6 back to the top of the list if that is what you want.

Tuesday, January 20, 2009

Grails Pitfalls and Tips

I have worked with Grails for some time now and thought I would share some of the common mistakes I have made early on. I also thought I could discuss some things that can make developing with Grails easier. Here is my short list of items:

Zero Turnaround Time

One of the convenient features of Grails is the ability to make a change and have that change be available immediately in your application. This is an obvious time saver and allows you to be more productive while developing your application. However, there are times when you will make major refactoring changes on the fly that the JVM cannot deal with. An example of this might be when you introduce something new in the middle of an existing class hierarchy. While it may appear that Grails is happy and your environment is sailing along you might see odd behaviour in the application and see some strange runtime exceptions along the way. What usually remedies this situation is instructing Grails to rebuild the internal structures in your application. This can be done by executing the following command and restarting your application:

# grails clean

Grails Console

One tool that you will want to keep in your Grails toolkit is the Grails console. This allows you to run a your application in an enviroment so you can experiment with code on the fly. One of the main reasons I do this is to try out my unit and integration code in the console before, or during, writing my tests. This is a fast way to get confidence that your test code will provide the results you want. And because you are doing this in the console you do not have to keep executing the grails test-app command to reinitialize the environment.

Since you have the full environment in the Grails console you can easily get references to your Spring beans and services. You are automatically provided a reference to the org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext class with a variable named ctx. This allows you to do things like this in the Grails console:

def service = ctx.bookStoreService
def book = service.getCurrentBook()
println "The most recent book is ${book.name} by ${book.author}"
println book.dump()
You can see all of the defined beans that Grails is aware of like this:

ctx.beanDefinitionNames.sort().each {println it}

Manually Assigning Primary Keys

Most of the time your domain objects will have autogenerated primary key values for the id field. However, I ran into a situation where I needed to manually assign a primary keys for one of my domain objects. This took a little bit of trial and error to make this work. Here is how you do this correctly:

          
String id
static mapping = {
id generator:'assigned', column:'RECORD_ID', type:'string'
}

Also note that you must set the id manually outside of the object constructor on a separate line like this:

def obj = new MyDomainObject(name:'whatever')
obj.id = 'REC000001'
obj.save(flush:true)

Not like this:

def obj = new MyDomainObjects(name:'whatever', id:'REC000001')
obj.save(flush:true)

because the value will not be saved.

Manually Triggering Quartz Jobs in Grails

Grails has an excellent plugin for managing scheduled Quartz jobs. However, I had a situation where I wanted to manually schedule a job. I could not find this in the documentation so after poking around in the source I figured out how to do this using the following technique. First you have to define the job name and group like this:

class MyValidationJob {

def name = 'MyJobName'
def group = 'MyGroup'

// your executable job method here...
}

Then you can manually trigger the job like this:

          // trigger the job manually by job name and group from your controller/service/whatever
def quartzScheduler // inject this in your class
quartzScheduler.triggerJob("MyJobName", "MyGroup")

Using Packages in the Grails

Grails provides a directory structure for your application components by convention similar to Rails. However, this can cause issues if you put your classes directly inside of these folders because they seen by Java in the default package. Using the default package can cause you issues when compiling your classes. Since we are using Groovy (and really Java) it is my opinion that you should add packages to your Groovy classes. I also think that modules in Ruby translate better than package structures at this point but we are stuck with Java constraints.

You can add packages to the provided services and domain folders and Grails will make Spring beans out of them. You just need to be careful not to use the same name for the bean twice. You just reference the bean by the name of the class. For example let's say you have a service called com.myco.service.validation.MyValidationService. Grails will expose this as a bean reference named myValidationService.


Base Classes with GORM

It is common practice that developers make a base domain class with common features of your subclassed domain objects. By defining an abstract class you can define common properties for your domain objects. There is a catch however. The GORM DSL allows you to define constraints and mappings blocks in these classes for validation purposes and defining ORM mappings respectively. The current problem is that if your subclasses have their own mappings and/or constraints defined they will override what is in your superclass instead of being merged with the superclass blocks. I am hoping that a future version of Grails addresses this issue (1.1 hopefully).


Unexpected NPEs

One of the earliest mistakes I made when working with Grails was generating NullPointerExceptions without much to decipher in the stack trace. The most common problem for me (which you will overcome quickly) was to make sure you validate your domain objects and handle the errors appropriately in your controllers. The errors object is automatically added to your domain objects and can be checked with the hasErrors method on those objects.


Viewing the Source of your GSP Files

This is just a quick tip that allows you to view the generated source of you GSP files. This is a simple as adding the 'showSource' parameter to your URL like this:

http://localhost/yourapp/yourController/list?sort=dateCreated&max=20&showSource

Monday, September 8, 2008

Generating GORM Domain Classes

I am on a project that already had a legacy database in place with about 100 tables. I did not want to create my GORM domain classes manually for my Grails project. I am surprised that I did not find any existing code to handle this code generation so I created a Groovy script to handle this. I am sure this code could use some improvements such as handling more SQL types so I will just call it a 0.1 release because it does what I needed for now. Modify the sql varible so it has the right database connection information. Also, modify the tables hash so you can control which domain classes to generate based on a [tableName:className] structure.

   1  import groovy.sql.Sql
2 import java.sql.Types
3
4 sql = Sql.newInstance("jdbc:mysql://localhost:3306/pts_development",
5 "root",
6 "password",
7 "com.mysql.jdbc.Driver")
8
9 // tables hash format => table : className
10 tables = ['PTS_REG_DTL':'Detail','PTS_REG_MST':'Master']
11 tables.each { table, className ->
12 File file = new File("${className}.groovy")
13 sb = new StringBuilder()
14
15 fieldNames = []
16 fieldTypes = []
17
18 query = "select * from ${table}"
19 sql.query(query.toString()){ rs ->
20
21 sb << "class ${className} {\n"
22
23 def meta = rs.metaData
24 if(meta.columnCount <=0) return
25
26 for(i in 1..meta.columnCount){
27
28 fieldName = meta.getColumnName(i).toLowerCase().replaceAll(/_[\w]/,{ it[1].toUpperCase()})
29 fieldNames << fieldName
30 fieldType = ""
31
32 switch(meta.getColumnType(i)) {
33 case Types.BIGINT:
34 fieldType = "Long"
35 break
36 case [Types.BINARY, Types.BIT, Types.BOOLEAN, Types.SMALLINT]:
37 fieldType = "Boolean"
38 break
39 case [Types.CHAR, Types.VARCHAR]:
40 fieldType = "String"
41 break
42 case [Types.DATE, Types.TIMESTAMP]:
43 fieldType = "Date"
44 break
45 case [Types.DECIMAL, Types.FLOAT]:
46 fieldType = "Decimal"
47 break
48 case [Types.INTEGER, Types.NUMERIC]:
49 fieldType = "Integer"
50 break
51 default:
52 fieldType = "Object"
53 }
54 fieldTypes << fieldType
55 sb << "\t${fieldType} ${fieldName}\n"
56 }
57
58 // Print out the table mappings
59 sb << "\tstatic mapping = {\n"
60 sb << "\t\ttable '${table.toString()}'\n"
61
62 for(j in 1..meta.columnCount) {
63 sb << "\t\t${fieldNames[j-1]} column:'${meta.getColumnName(j)}'\n"
64 }
65 sb << "\t}\n"
66
67 // Print out the table constraints
68 sb << "\tstatic constraints = {\n"
69
70 for(k in 1..meta.columnCount) {
71 sb << "\t\t${fieldNames[k-1]}("
72 sb << "nullable:${meta.isNullable(k) ? 'true': 'false'}"
73
74 if(fieldTypes[k] == 'String') {
75 sb << ", maxSize:${meta.getColumnDisplaySize(k)}"
76 }
77 sb << ")\n"
78 }
79 sb << "\t }\n"
80 sb << "}\n"
81 }
82 file.write(sb.toString())
83 }

This code will generate a separate file for each domain class you specified in the tables hash in the current directory. Just make sure you have your database jar file in your classpath. Here is how you could run this code from the command line:

groovy -cp .:/Users/meagle/java/api/mysql-connector-java-5.0.4/mysql-connector-java-5.0.4-bin.jar GormGenerator.groovy

Friday, August 15, 2008

Securing a Grails application with Acegi and Crowd (Revisited)

I recently had a need to combine these technologies to provide authentication and authorization with Crowd in my Grails application. I ran across a very good article that handholds you through this process. You can reference the original aricle here.

However, I ran into several issue when I tried to apply the configuration in the article. The original article uses Grails 1.0.1, the Acegi Security Plugin v0.2, and Crowd 1.3. When I attempted to follow the instructions I attempted to use Grails 1.0.3, the Acegi Security Plugin v0.3, and Crowd 1.4. If you are still reading then make sure that you continue to use 0.2.1 version of the plugin because the Crowd integration module has not been updated to reference the latest Acegi/Spring Security framework updates such as pack naming. From here I will reference where you will need to make modifications for each step that requires it in the original article.

Step 1: Grails & Acegi Installation

Again, use the Acegi Security Plugin v0.2.1

Step 2: Create Grails Application with Acegi Security

Download and install the Acegi Security Plugin v0.2.1 in your Grails project.

Step 3: Crowd Download

Download Crowd v.1.4.4 from the Atlassian website.

Step 4: Crowd Installation & Configuration

The installation and configuration is surprisingly as easy as the original author suggests. Just follow the installation instructions.

Step 5: Grails + Acegi + Crowd Integration

Make absolutely sure that you do not skip the step regarding crowd.properties. If the application name and password do not match the same values in the application configuration you will not be allowed to attempt authentication against Crowd. You can setup these values in the Crowd administration console by navigating to the Applications tab and selecting the application from the list. From there click the Details tab and ensure the name and password are set to the same values as crowd.properties. Also, make sure that the application.login.url value is modified to the correct login url. The one specified in the article should be consistent with the example.

I did follow the author's lead and copied the applicationContext-CrowdClient.xml file from the
CROWD_HOME/client/crowd-integration-client-1.4.4.jar file and positioned it in the ACEGI_APP/conf/spring/ directory and then renamed the file to resources.xml.

The modifications I had to make to resources.xml were different from the author's article. Here are the beans I added:

   1  <bean id="crowdUserDetailsService" class="com.atlassian.crowd.integration.acegi.user.CrowdUserDetailsServiceImpl">
2 <property name="authenticationManager" ref="crowdAuthenticationManager"/>
3 <property name="groupMembershipManager" ref="crowdGroupMembershipManager"/>
4 <property name="userManager" ref="crowdUserManager"/>
5 <!--<property name="authorityPrefix" value="ROLE_"/>-->
6 <property name="authorityPrefix" value=""/>
7 </bean>
8
9 <bean id="crowdAuthenticationProvider" class="com.atlassian.crowd.integration.acegi.CrowdAuthenticationProvider">
10 <property name="userDetailsService" ref="crowdUserDetailsService"/>
11 <property name="authenticationManager" ref="crowdAuthenticationManager"/>
12 <property name="httpAuthenticator" ref="httpAuthenticator"/>
13 </bean>
14
15 <bean id="crowdLogoutHandler" class="com.atlassian.crowd.integration.acegi.CrowdLogoutHandler">
16 <property name="httpAuthenticator" ref="httpAuthenticator"/>
17 </bean>
18
19 <bean id="logoutFilter" class="org.acegisecurity.ui.logout.LogoutFilter">
20 <constructor-arg value="/"/>
21 <constructor-arg>
22 <list>
23 <ref bean="crowdLogoutHandler"/>
24 <bean class="org.acegisecurity.ui.logout.SecurityContextLogoutHandler"/>
25 </list>
26 </constructor-arg>
27 <property name="filterProcessesUrl" value="/j_acegi_logout"/>
28 </bean>
29
30 <bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
31 <property name="filterInvocationDefinitionSource">
32 <value>
33 CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
34 PATTERN_TYPE_APACHE_ANT
35 /images/**=#NONE#
36 /scripts/**=#NONE#
37 /styles/**=#NONE#
38 /**=httpSessionContextIntegrationFilter,logoutFilter,authenticationProcessingFilter,securityContextHolderAwareRequestFilter,rememberMeProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor
39 </value>
40 </property>
41 </bean>

AcegiGrailsPlugin.groovy


Instead of making this modification to this file I put the change inside of resources.xml. If you make this modificaiton inside the plugin code and you upgrade it you will need to remember this. Instead Grails will override the authenticationManager in AcegiGrailsPlugin with this definition inside of resources.xml:

   1      <bean id="authenticationManager" class="org.acegisecurity.providers.ProviderManager">
2 <property name="providers">
3 <list>
4 <ref local="crowdAuthenticationProvider"/>
5 <ref bean="anonymousAuthenticationProvider"/>
6 <ref bean="rememberMeAuthenticationProvider"/>
7 </list>
8 </property>
9 </bean>

Wednesday, April 30, 2008

Deploying Rails 2.0.2 applications with Tomcat 5.5.x using Warbler

After working with Rails for some time I wanted to determine how to deploy an application on Tomcat. I will discuss how to build a war file that can be used on Tomcat and show pitfalls I experienced along the way. Here are the technologies I am using for this deployment:
  • JRuby 1.1.1
  • Rails 2.0.2
  • Warbler 0.9.5
  • MySQL 5.0.4
To package up my Rails application I am using Warbler as indicated above. This is an alternative to Goldspike but allows a better packaging scheme and an easier configuration. Warble is actually a wrapper to Goldspike and includes these dependencies when you install the gem. You can read more about Warbler here.

I will assume you have Rails installed as a gem in JRuby. To make a standalone war file make sure you run this command to freeze Rails in your project:

$ jruby -S rails:freeze:gems

This will write the standard Rails gem information to your RAILS_ROOT/vendor/rails directory. Here is how you install Warbler from JRuby:

$ jruby -S gem install warbler

After this is configured switch to the root of your Rails project and execute this command:

$ jruby -S warble

This will build an exploded war file in a temporary directory within your project. This path can be changed in the warble.rb file that gets installed. Now create a Warble configuration file by executing this command since we will need it (not sure why this is done after the fact):

$ jruby -S warble config

After generating a configuration file you should consider updating the JRuby jar file that comes with Warble since you will want the latest version packaged with your war file. If you do not do this Warble will always include the original version of the JRuby jar with your war file. Add the jruby-complete-1.1.1.jar file which can be obtained here) to your RAILS_HOME/lib directory. Grab the latest Goldspike jar file and place it in your RAILS_HOME/lib directory. Now add this code to the configuration:

config.java_libs.reject! {
|lib| lib =~ /jruby-complete|goldspike/
}


This allows you to externally package your own versions of JRuby and Goldspike and reject the verions of these jar files that come bundled in the gem directory ($JRUBY_HOME/lib/ruby/gems/1.8/gems/warbler-0.9.5/lib/warbler).

Also, you can delete the exploded directory and the war file by issuing this command:

$ jruby -S warble war:clean

From this point you just move the war file to your Tomcat webapps directory and start the server. This is great when everything works. However, I was lucky enough to run into some issues while making this happen.

The first issue occurred when I started Tomcat with the war file I built with Warble (remember that this is using Goldspike under the covers) and got this error message in the Tomcat logs:

“Could not load Rails. See the logs for more details.”

Yipee! So when I went to look in the Tomcat logs there was no additional information. Great! It turns out that the stack trace output gets swallowed on a Mac. This is fairly easy to fix (but should be patched by the Goldspike team) by modifying the source code for the goldspike-1.6.1.jar file to emit the full stack trace. Grab the latest Goldspike code from here:

svn checkout
svn://rubyforge.org/var/svn/jruby-extras/trunk/rails-integration


You will have to modify src/main/java/org/jruby/webapp/RailsFactory.java like this:

} catch (RaiseException e) {
//added this line so the full stack trace is shown
e.printStackTrace();

logRubyException("Failed to load Rails", e);
throw new ServletException(
"Could not load Rails. See the logs for more details.");
}
After you rebuild the Goldspike jar add it to your RAILS_ROOT/lib. Now re-warble your war file and put it on your Tomcat server. Now you should be able to find your error. In my case I was not making a connection to my database. I was clearly missing gems in my war file. Great!

This really is not too big of a deal. You can explain to Warbler what gems need to be packaged with your war file. Here is a snippet from my warble.rb file that shows how I included the missing gems:

# Gems to be packaged in the webapp. Note that Rails
#
gems are added to this list if vendor/rails is not
#
present, so be sure to include rails if you overwrite
# the value

config.gems = ["activerecord-jdbc-adapter", "jruby-openssl", "activerecord-jdbcmysql-adapter", "jdbc-mysql"]


Alright re-warble and... still no connectivity. Awesome! This time I was missing my MySQL jar file in my war file and the activerecord-jdbcmysql-adapter gem could not communicate with the implementation jar. To fix this copy your MySQL jar file to the RAILS_ROOT/lib directory in your Rails project.

One more re-warbling and more good news:

“Rails Error: No :secret given to the #protect_from_forgery call. Set that or use a session store capable of generating its own keys (Cookie Session Store)”.

This is a known bug with Goldspike and Rails 2.0. So edit your web.xml file and add the following:
<context-param>
<param-name>jruby.session_store</param-name>
<!-- This value really means let Rails take care
of session store -->
<param-value>db</param-value>
</context-param>
OK, please just one more re-warbling and deployment to Tomcat and a successful standalone war file has been created and deployed. *birds singing*

I would also suggest increasing the Java memory setting in the JAVA_OPTS of Tomcat to at least -Xmx512m to improve performance. Also keep in mind that Warble is configured to use the production environment for your Rails application so make the appropriate migrations before starting the application. You can make further modification to the Goldspike configuration within the warble.rb file to tweak the pool of Rails runtimes. Once I made these changes it was pretty transparent where I was running my Rails application.

I hope this saves other people time when running into issues. This was kind of a frustrating process since it should be a simple one line deployment. However, I was happy with the end results.

Friday, January 18, 2008

Migrating to Grails?

The last time I looked at Grails it was around version 0.4. Now that we are approaching a 1.0 release I wanted to see how much further the Grails team has advanced. I wanted to start by using my existing Spring and Hibernate components from my Java project (I am currently using Stripes for our presentation layer). Benefits for doing this might include:
  • Abstracting your Java domain model and services so they are not coupled to Grails.

  • The ability to continue using your Java services and model objects outside of Web applications or have the ability to integrate with other Web presentation frameworks.

  • A migration path to Groovy if you want to rid yourself of straight Java altogether. I am sure that there would be massive redux in LOC. For me it was experimenting with the intersection of my experiences with Rails and Java Web development.

Does this mean that if you reuse your Hibernate Java domain objects you do not get all of the GORM features like (order.save())? No, your domain objects transparently take full advantage of the mixed in methods in Grails. You might find that the services you are reusing from Spring are mostly passthroughs to DAO that you do not need anymore because of GORM. Here is a trivial example showing how to use a Grails controller to use existing Spring services to perform DAO operations and how to use your Hibernate domain objects directly as GORM objects:


UserService userService  // This is injected in via auto-wiring

def index = {

// Using Java Services
def user = userService.find(1, User.class)
println user.firstName
user.firstName = 'Mark'
userService.save user
println User.get(1).firstName

// Using strait Grails
user = User.get(1)
println user.firstName
user.firstName = 'Phil'
user.save()
println User.get(1).firstName
}

Here is how we took our annotated Hiberate classes so Grails would recognize them:

Edit your hibernate.cfg.xml file in the GRAILS_APP/grails_app/conf/hibernate directory and add your domain objects:

<!DOCTYPE hibernate-configuration SYSTEM
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="com.meagle.common.bo.Address" />
<mapping class="com.meagle.common.bo.User" />
</session-factory>
</hibernate-configuration>
In your DataSource.groovy configuration file add the configClass line to your datasource configuration so your annotated Hibernate classes will be recognized by Grails:
dataSource {
pooled = false
driverClassName = "com.ibm.db2.jcc.DB2Driver"
username = "meagle"
password = "******"
configClass
=org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration.class
}
Here is how you expose your existing Spring beans to your Grails application:
  1. Edit your GRAILS_APP/grails_app/conf/spring/resources.xml file and add the following line:
    <import resource="applicationContext-core.xml"/>
    This tells Grails to include your Spring resources (We put our Spring config file in the same directory as the resources.xml file).

  2. Make sure all of your Spring and Hibernate domain objects written in Java are on the classpath. We put ours in a jar file in the GRAILS_APP/lib directory.

One gotcha here to remember is that your Spring configuration file should not include any definition to a SessionFactory and your services and DAOs that reference a SessionFactory needs to be the name "sessionFactory". Otherwise, you will end up with multiple session factory objects which is probably not what you want.

Overall I am very impressed with Grails at this point and would challenge Java developers to take a serious look at this framework. If you are fortunate enough to have IntelliJ 7 then there is decent plugin support for building Grails applications.

Saturday, December 15, 2007

NetBeans 6.0 and Rails

I have been looking for a good Rails IDE and think I have found one. I was using TextMate which has lots of great quick templating commands for Rails concepts for migrations, rhtml, and navigating between files and methods. However, I enjoy working with IDEs and tried some Eclipse based versions but felt that they were inadequate. My paying job at the time is mostly Java based and I use IntelliJ which makes my development more productive for that type of development.

I had not looked at NetBeans in some time because most Java developers were using Eclipse and that was fine for me at the time. So when I saw that NetBeans had a Rails related version of their IDE I was willing to give it another look. I can only say that for me this is a very nice IDE that has full functionality around the way I develop with Rails. Here are some of the features I find handy:

  • A simple IDE layout for components that is similar to IntelliJ. There are no unnecessary perspectives that Eclipse users have.
  • Support for auto-completion of methods with rdoc helpers.
  • Debugging capabilites that are simple to use.
  • Integration with version control repositories like Subversion.
  • Tools to manage your Gems and Plugins from the Tools menu
  • Easy navigation between Rails controllers and views as well as opening files via keystrokes.
  • Decent refactoring built in
  • Generators for creating Rails components.
  • Menus to run Rake and Migration scripts
  • Built in functionality to start a Rails console from your project
  • It works great on my Mac and much more than I expected...


  • Just to whet your appetite to get you more excited about this IDE here are a couple of screenshots from how I use this IDE:
    Here is what it looks like when editing files with code completion and quick docs:



    And here is a shot of what debugging looks like in NetBeans:



    If you are working on a Mac make sure you look at this link for setting up the fast debugger gem. You will also need to have XCode installed for compilation.
    I think you will agree that this is the best IDE for Rails at this time.

    Monday, March 5, 2007

    Java Through Ruby Through Java

    Java => Ruby

    Now that JRuby has matured I thought I would see what it would take to inject Java objects into Ruby objects via a Spring context. Here is how this works:

    First, create a Ruby class that will receive your Java objects:

    ruby_messenger.rb:

    require 'java'

    include_class 'com.meagle.common.spring.jruby.JRubySpring'
    include_class 'com.meagle.common.service.UserService'
    include_class 'com.meagle.common.service.impl.BaseUserServiceImpl'

    class RubyMessenger < JRubySpring

    def printMe
    p @@message
    p @@userService.to_s
    user = @@userService.findUser('admin')
    p "User first name: #{user.firstName}"
    #p user.to_xml
    end

    def setMessage(message)
    @@message = message
    end

    def getMessage
    @@message
    end

    def setUserService(userService)
    @@userService = userService
    end

    end

    RubyMessenger.new # this last line is not essential (but see below)
    This class will receive a user service object that allows us to make calls to a transactional Spring bean to a DAO defined in the main Spring configuration.

    Furthermore, I am injecting a simple String into the Ruby class from the Spring context called 'message'. Notice that the class extends an interface in Java called JRubySpring. This interface is used to expose methods on the Ruby object to our Java application. Here is what this Java interface looks like:

    JRubySpring.java:

    public interface JRubySpring {
    void printMe();

    void setUserService(UserService service);

    String getMessage();

    void setMessage(String message);
    }
    Now we have to tell Spring about our Ruby class and the properties to inject into the class. This can be wired up in a Spring 2.0 context configuration file like this:

    applicationContext-jruby.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/lang
    http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">

    <?xml version="1.0" encoding="UTF-8"?>

    <lang:jruby id="jrubyService"
    script-interfaces="com.meagle.common.spring.jruby.JRubySpring"
    script-source="classpath:ruby_messenger.rb">

    <lang:property name="message" value="Hello from Ruby!"/>

    <lang:property name="userService">
    <ref bean="userService"/>
    </lang:property>

    </lang:jruby>

    </beans>

    This instructs Spring to use the ruby_messenger.rb class from the classpath and allow Java classes to use the JRubySpring interface to invoke methods on the Ruby class. Furthermore, you can see the properties that are being injected into the Ruby class here.

    Finally, we need a way to test this out. Again, Spring can help us test this using the AbstractSpringIntegrationTestBase class to help with initializing a Spring context and running test scenarios. Here is the test class:

    JRubySpringTest.java

    public class JRubySpringTest extends AbstractSpringIntegrationTestBase {
    private UserService userService;

    public JRubySpringTest() {
    setDefaultRollback(true);
    }

    protected String[] getConfigLocations() {
    return new String[]{
    "applicationContext-core.xml",
    "applicationContext-jruby.xml"
    };
    }

    JRubySpring jrubyService;

    public void testGetUser() {
    System.out.println("Printing messages from plain old Java Spring context...");
    System.out.println(jrubyService.getMessage());
    User user = userService.findUser("admin");
    System.out.println("user = " + user.getFirstName());
    System.out.println("Printing messages from a Spring context injected
    into a Ruby object...");
    jrubyService.printMe();
    }

    public JRubySpring getJrubyService() {
    return jrubyService;
    }

    public void setJrubyService(JRubySpring jrubyService) {
    this.jrubyService = jrubyService;
    }

    public void setUserService(UserService userService) {
    this.userService = userService;
    }
    }
    This test class will initialize Spring and autowire the Ruby class into the test class with the Java/JRuby properties injected into the Ruby class as singletons.




    Here is some sample output when running this test class:

    03.05.2007 13:30:40,062 INFO dao.hibernate.JRubySpringTest.startNewTransaction:318 ->
    Began transaction (1): transaction manager [org.springframework.orm.hibernate3.HibernateTransactionManager@1284f8e]; default rollback = true

    Printing messages from plain old Java Spring context...

    Hello from Ruby!

    user = System

    Printing messages from a Spring context injected into a Ruby object...

    "Hello from Ruby!"


    "com.meagle.common.service.impl.BaseUserServiceImpl@595bcd"

    "User first name: System"

    03.05.2007 13:30:40,312 INFO dao.hibernate.JRubySpringTest.endTransaction:284 ->
    Rolled back transaction after test execution
    03.05.2007 13:30:40,328 INFO context.support.ClassPathXmlApplicationContext.doClose:599 ->
    Closing application context [org.springframework.context.support.ClassPathXmlApplicationContext;hashCode=6504030]

    Ruby => Java

    So what if you want to have an irb session and communicate with your Java objects. For this you just need your existing Spring context and a bootstrapping file for Ruby to initialize a JRuby console. It goes like this:

    jruby_console.rb

    # To use JRuby and Java Spring contexts together do the following:
    #
    # 1. Download the JRuby irb jar file from:
    # http://jruby.codehaus.org/Running+the+JRuby+Console+(graphical+IRB)
    #
    # 2. Add the jruby-console-0.9.2.jar file to your Java project classpath
    #
    # 3. Create a new configuration to run a Java application and set the main class to
    # org.jruby.demo.IRBConsole
    #
    # 4. Of course make sure your classpath is set correctly for your Spring config and
    # other classes/jars you need to test.
    #
    # 5. Run the application which will load the JRuby irb console
    #
    # 6. In the irb window type > load 'jruby_console.rb' to initialize this script.
    #
    # 7. This will load your Spring configuration. Access your Spring beans as
    # instance variables like this @beanName.
    #
    # 8. That was easy

    require 'java'

    # require this file if you want to include your domain objects instead of
    # including them one at a time.
    require 'domain_core.rb'

    # include this line to include all of your specific Java domain objects
    include Domain::Core

    include_class('org.springframework.context.support.ClassPathXmlApplicationContext')

    springConfigs = ["applicationContext-core.xml"]
    @context = ClassPathXmlApplicationContext.new(springConfigs.join(","))

    if @context.nil?
    p "*********Could Not initialize Spring context*********"

    return
    else
    p "*********Spring context initialized as @context*********"
    end

    p "(#{@context.beanDefinitionNames.length}) beans initialized in this context:"
    beans = ""

    # Assign non-abstract beans are initialized to instance variables.
    # Example: The 'userService' bean name will be accessible via the
    # instance variable '@userService'
    @context.beanDefinitionNames.sort.each do |bean|
    unless bean =~ /^abstract/
    instance_variable_set("@#{bean}", @context.getBean("#{bean}"))
    beans << bean + ", "
    end
    end

    p beans
    p "=========================================================================="
    p "Hey you - access your beans as instance variable like this @springBeanName"
    p "=========================================================================="

    Now you can do sadistic stuff like this:

     Welcome to the JRuby IRB Console

    irb(main):001:0> load 'jruby_console.rb'
    "*********Spring context initialized as @context*********"
    "(4) beans initialized in this context:"
    dataSource, sessionFactory, userDAO, userService"
    "=========================================================================="
    "Hey you - access your beans as instance variable like this @springBeanName"
    "=========================================================================="
    => true

    irb(main):002:0> user = @userService.find(33, User.new.class)
    => #

    irb(main):003:0> p user.firstName
    "Mark"
    => nil
    irb(main):004:0>

    Tuesday, December 5, 2006

    Autocompleting with Stripes and Scriptaculous

    I recently had to implement autocompletion AJAX functionality with script.aculous.us and Stripes. Once again this AJAX functionality was simple to integrate with Stripes. This code will return a list of users to select from after the user types more than two characters.

    Here is an example Stripes action that will be responsible for looking up the users and returning a partial page with the unorder list of users. In this example code the autoCompleteText will capture the text that will be autocompleted. A Spring bean will be used to call out to service which will use a Hibernate DAO to query for the user list.

     public class UserLookupAction implements ActionBean {

    String autoCompleteText;

    UserService userService;
    private List users;

    public Resolution findUsers(){
    this.users = userService.findUsersByAutocompletion(autoCompleteText);
    return new ForwardResolution("/pages/useradmin/FindUsers.jsp");
    }

    @SpringBean
    public void setUserService(UserService userService) {
    this.userService = userService;
    }

    public String getAutoCompleteText() {return autoCompleteText;}

    public void setAutoCompleteText(String autoCompleteText) {
    this.autoCompleteText = autoCompleteText;
    }

    public List getUsers() {
    return users;
    }

    public void setActionBeanContext(ActionBeanContext actionBeanContext);
    public ActionBeanContext getActionBeanContext() {return this.actionBeanContext;}
    }

    This JSP is responsible for making the AJAX calls to the Stripes action above. The AJAX.Autocompleter code from Scriptaculous does the work when more than two characters are present in the text field named autocomplete. If there are results they are returned in a partial page as an unordered list (more later). An animated gif indicator is used to signal the user that the AJAX call is being made and searching for results. Also, there is a callback method called getSelectionId that is called afterUpdateElement. This will be used to set the selected user id in a hidden field named autocompleteUserId. This will be used when editing the user through another Stripes action (UserEditAction).

     <style type="text/css">
    div.autocomplete {
    position:absolute;
    background-color:white;
    border:1px solid #888;
    margin:0px;
    padding:0px;
    }

    div.autocomplete ul {
    list-style-type:none;
    margin:0px;
    padding:0px;
    }

    div.autocomplete ul li.selected { background-color: #ffb;}

    div.autocomplete ul li {
    list-style-type:none;
    display:block;
    margin:0;
    padding:5px;
    cursor:pointer;
    border-bottom: 1px solid #cbcbcb;
    }
    </style>


    <%@ taglib prefix="stripes" uri="http://stripes.sourceforge.net/stripes.tld" %>

    <stripes:form beanclass="com.meagle.web.stripes.action.useradmin.UserEditAction">
    User Name:
    <stripes:text size="30" id="autocomplete" name="autoCompleteText"/>

    <div id="autocomplete_choices" class="autocomplete"></div>
    <script type="text/javascript">

    new Ajax.Autocompleter ("autocomplete",
    "autocomplete_choices",
    "${pageContext.request.contextPath}/useradmin/UserLookup.action?findUsers=",
    {minChars: 2, afterUpdateElement : getSelectionId, indicator: 'indicator1'});

    function getSelectionId(text, li) {
    $('autocompleteUserId').value = li.id;
    }
    </script>

    <stripes:hidden name="userId" id="autocompleteUserId"/>
    <stripes:submit name="editUser" class=class="code-quote">"textBox" value="Edit"/>

    <span id="indicator1" style="display: none">
    <img width=
    "14" height="14"
    src="${pageContext.request.contextPath}/images/indicator_circle_ball.gif"
    alt="Working..." />

    </stripes:form>
    Finally, this is the partial page that is returned by the UserLookupAction when results are returned. This simply iterates over the User objects from the Stripes action and creates an unorder list that is stylized with the CSS above.

     <%@ taglib prefix="c" uri=<http://java.sun.com/jsp/jstl/core> %>

    <ul>
    <c:forEach var="user" items="${ actionBean.users}">
    <li id="${user.id}">${user.firstName} ${user.lastName}</li>
    </c:forEach>

    </ul>

    Thursday, November 23, 2006

    AJUG Stripes Presentation

    Phil Barnes and I presented the Stripes framework at AJUG last night. We wanted to spread the word about Stripes and how it simplifies Java Web development. Most of the people who attended the presentation were using Struts as their presentation framework (no surprise here). We came prepared with many examples about how Stripes compared to Struts.

    I think that the presentation was well received and hopefully it will make people take another look at Stripes. We have researched many Java Web frameworks and this is probably the best one out there as far as simplicity while allowing the developer to focus on application development. Stripes uses convention over configuration for resolving URLs to action classes, has excellent databinding, and integrated well with other POJO based frameworks.

    Please contact me at meagle@gmail.com if you want a copy of the slides.

    Friday, April 28, 2006

    Stripes: I think we have a winner!

    For some time now I have been evaluating Java web frameworks. This was mostly driven by my frustration with existing frameworks I have been using. The amount of effort it takes to feed these frameworks to produce anything meaningful is usually painful and not fun to maintain. My baseline framework for Java Web development has been Struts. Struts is just outdated and requires way too many configuration files, extra classes outside the controller/action, and a separate ActionForm class that requires crude object binding. Enough said. From Struts I investigated a slew of frameworks such as Tapestry, Wicket, Spring MVC, and some JSF. These frameworks were definitely better than Struts (not too hard to achieve) but never felt much more productive and varied in learning curves. Then I started to investigate WebWork. This was definitely a step in the right direction. WebWork is an action based framework that is the basis for the Struts Action 2.0 Framework. WebWork does offer simpler actions, less configuration, some AJAX support, different view resolvers, interceptor stacks, and much more. We even decided to use WebWork for our new project after we felt that it addressed most of our concerns and there was nothing better to work with. We did experience more than a 40%+ reduction in the number lines of code and configuration files we had to write. This was great until...

    The Stripes project recently released version 1.3 of their web framework. This framework relies heavily on Java 5 capabilities to deliver a much simpler web framework. The configuration is done up front in the web.xml file where a filter and a Servlet dispatcher is configured. The only thing that you need to be aware of is to configure the root package of your Stripes action classes. This allows Stripes to inspect your action classes when your servlet container starts up. Stripes uses a convention based approach to determine which classes in this defined package will be Stripes actions. Therefore, action classes do not have to be configured in an XML file. That's right - no more struts-config, xwork.xml, JSF config nonsense, etc.

    From this point on you are ready to code. The action classes that you build contain concise annotations that handle interception, validation, Spring integration, and more. With your classes annotated you do not have to flip back and forth between external files and your action classes. This saves you a ton of time and reduces lines of code. In fact we migrated our WebWork code to Stripes equivalents and experienced another 20%+ reduction in the lines of code (and removing configuration files) while maintaining full functionality. Not too bad. The migration only took about 2 days to complete for about 8 complex actions and 12 JSPs. As you can see will be using this on all of our projects.

    The only con I can think of for Stripes is that you have to use JSP and the Stripes taglibs. However, the taglib is pretty good and very close to HTML in regards to the naming used. I am hoping that a Velocity view resolver is on the horizon in the not too distant future. However, I did not experience too many problems with JSTL and the Stripes taglib.

    If this sounds good take a look at the Stripes Quick Start Guide to quickly get up and running. Stripes is a great step forward for Java web development. It offers Java developers an simple way to program Java web applications with minimal configuration, high productivity, and a fun development framework that is addictive. This might be as close to the Ruby on Rails Action Pack for MVC development as we will see in a while from the Java community.

    Tuesday, March 28, 2006

    Comparing Web Frameworks: WebWork

    Lately there have been Java Web framework comparisons on theServerSide.com. These comparisons revolve around requirements on Simon Brown's Blog. I am not sure that the application is very relevant and has limited functionality. However, I decided I would try this with WebWork. I have been using WebWork for about 5 months now and have been very productive with the framework's capabilities and ease of use. I took the requirements for the read only blog and reproduced it with WebWork. There is really very little that needed to be coded to make this happen and I did this on a plane trip from Atlanta to Las Vegas where I am attending TSSS with only one battery in my notebook.

    To save time I copied some of the components from other people's implementations that were not framework specific.This included the domain objects Blog, BlogEntry, and BlogService. Theseare straightforward and I could have generated them in IntelliJ in about 2 minutes so no big deal. I also copied the stylesheet and image that was used to pretty up the blog look and feel. Again, no big deal and not really relevant to the framework comparison. So let me take a moment to preface some of my gripes with this little project. First, I do not consider someof the methods I used to code this application to be ideal. Since this is a read only blog application I did not use a persistence mechanism for the blog entries.

    Nevertheless, I coded the application to the specifications required using only the WebWork web tier components no more. The main WebWork component that needed to be designed was the action class. This is fairly lean and should be
    easy to interpret. Here is the code:

    public class BlogAction implements Preparable {

    private Blog blog;
    private BlogEntry blogEntry;
    private String blogEntryId;
    private BlogService blogService;

    public void prepare() throws Exception {
    blog = getBlogService().getBlog();
    }

    public String execute() {
    // simply display the default page -- the data was setup in prepare()
    return "success";
    }

    public String viewBlogEntry() {
    this.blogEntry = blog.getBlogEntry(this.blogEntryId);

    return "entry";
    }

    public void setBlogEntryId(String blogEntryId) {
    this.blogEntryId = blogEntryId;
    }

    public Blog getBlog() { return blog; }

    public BlogEntry getBlogEntry() { return blogEntry; }

    protected BlogService getBlogService() {
    if (blogService == null) {
    blogService = new BlogService();
    }
    return blogService;
    }

    public void setBlogService(BlogService blogService) {
    this.blogService = blogService;
    }

    }

    This is about 40 lines of code and most of that is comments, fields, and accessors. Really there are only about 5 lines of code of any logic. The prepare method is called before the action executes to setup the action. This gets called because the action implements the Preparable interface. The Prepare interceptor is invoked as one of the interceptors in the default interceptor stack. The service should really be injected into the action by an IoC container such as Spring (WebWork has good integration support with Spring). Also notice that other than implementing the Preparable interface this action is just a POJO.

    Here is the action configuration in the xwork.xml file:
       <action name="Blog" class="com.meagle.wwblog.web.webwork.actions.BlogAction">
    <result name="success">/pages/index.vm</result>
    <result name="blogentry">/pages/entry.vm</result>
    </action>
    As for the views there were two files. The first one shows the blog and associated entries. I used SiteMesh todecorate the common elements and JSP as the view resolver to display the stack elements. WebWork can also use Freemarker, Velocity, and other view resolvers as well. Here is what the Sitemesh decorator looks like:
         <%@ page pageEncoding="UTF-8"%>
    <%@ page contentType="text/html; charset=utf-8"%>

    <%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
    <%@ taglib prefix="ww" uri="/webwork" %>
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
    xml:lang="en"
    lang="en">

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title><decorator:title default="Welcome!" /></title>
    <meta http-equiv="Content-Style-Type" content="text/css">
    <link rel="stylesheet" href="/css/screen.css" type="text/css"/>
    </head>

    <body>
    <div id="container">
    <h1><decorator:title default="Welcome!" /></h1>

    <h2><ww:property value="%{blog.description}"/></h2>

    <decorator:body />
    </div>
    </body>

    </html>

    So this takes care of the blog title, name, and description that appears on each page. This also leaves a placeholder for the content of each page. Here is what was required to display the entries in the blog:

         <%@ page pageEncoding="UTF-8"%>
    <%@ page contentType="text/html; charset=utf-8"%>
    <%@ taglib uri="/webwork" prefix="ww" %>
    <html>

    <head>
    <title><ww:property value="%{blog.name}"/></title>
    </head>
    <body>
    <table>

    <ww:iterator value="blog.blogEntries" id="blogEntry">
    <tr>
    <td>
    <div class="blogEntry">
    <h3><ww:property value="title"/></h3>

    <div>
    <ww:if test="excerpt != null">
    <ww:property value="excerpt" escape="false"/>
    </ww:if>
    <ww:else>
    <ww:property value="body" escape="false"/>

    </ww:else>
    </div>

    <p>
    <ww:if test="excerpt != null">
    <ww:url id="readMoreUrl" action="Blog!viewBlogEntry">
    <ww:param name="blogEntryId" value="id"/>

    </ww:url>
    <a href="<ww:property value="readMoreUrl" escape="false"/>">Read More</a>
    </ww:if>
    </p>

    <p>
    Posted on <ww:date name="%{date}" format="dd MMMM yyyy hh:mm:ss z"/>
    </p>
    </div>
    </td>
    </tr>

    </ww:iterator>
    </table>
    </body>
    </html>

    Again, this is straightforward and captures the requirements of the application. The only interesting lines here that allows the user to conditionally view more of a blog entry is this:

          <ww:url id="readMoreUrl" action="Blog!viewBlogEntry">
    <ww:param name="blogEntryId" value="id"/>
    </ww:url>
    <a href="<ww:property value="readMoreUrl" escape="false"/>">Read More</a>

    These lines create a link that calls the viewBlogEntry method of the Blog action by using a WebWorkconvention. The blog entry ID is appended as a parameter so that we can display the correct blog entry. You may notice the "action" in the tag references our Action class method viewBlogEntry(); it's in this method that we pull the specific entry and expose it (via a class variable) so that the view layer can render the entry. Here is the code for the view for displaying the entry.

         <%@ page pageEncoding="UTF-8"%>

    <%@ page contentType="text/html; charset=utf-8"%>
    <%@ taglib prefix="ww" uri="/webwork" %>
    <html>
    <body>
    <ww:if test="blogEntry != null">
    <div class="blogEntry">

    <h3><ww:property value="blogEntry.title" escape="false"/></h3>

    <div><ww:property value="blogEntry.body" escape="false"/></div>

    <p>
    Posted on <ww:date name="%{blogEntry.date}" format="dd MMMM yyyy hh:mm:ss z"/>

    </p>
    </div>
    </ww:if>
    <ww:else>
    <div class="blogEntry">
    <h3>Sorry we could not locate that blog entry...</h3>

    </div>
    </ww:else>
    <div><a href="JavaScript:void(0)" onclick="history.go(-1)">Back</a></div>
    </body>
    </html>

    That is really all there was to coding the requirements of the application. The rest of the components were skeleton elements from a base WebWork configuration.

    Conclusion

    While this is a very simplistic web application with little functionality it does show how little coding is required by WebWork to make it happen. There is so much more that I would have like to have shown such as some of the data binding capabilities inside WebWork when submitting form information with complex object graph information.

    This trivial application really does not show WebWork's full capabilities. If you think there is value in this example then you should give WebWork a try on more complex applications.
    WebWork makes coding web development with Java simple and very productive with the framework's capabilities and ease of use.