Mastering Grails: The Grails Event Model (Scott Davis)

, August 14th, 2008

Original Source

DeveloperWorks has published the latest installment of Scott’s Mastering Grails series: The Grails Event Model. This article lays out the basis for event handling in Grails, both at the macro and micro levels. The macro level is build and application wide. Grails (and its huge library of plugins) usually publish events whenever a script runs or an artifact is changed, according to the plugins needs. You have the option to listen on those events and react accordingly. The micro level happens at the domain layer, where domain classes publish four events whenever they interact with the database.

Building a Web site is a study in event-driven, reactive development. Your application sits idle, anxiously waiting for the user to send in a request. It passes back the response and then goes back to sleep until the next call. In addition to the traditional Web life cycle of HTTP requests and responses, Grails provides a number of custom touch points where you can tap into the event model and provide behavior of your own.

In this article, you’ll discover the myriad of events being thrown in during the build process. You’ll customize the startup and shutdown of your application. And finally, you’ll explore the life cycle events of Grails domain classes.

Scott demonstrates in a few and simple steps how to plug into Grails’ events on the macro level (build), his recommendation is that once you get used to working with events you place your event handler scripts inside the project’s script directory, that way your customization will be saved in version control too. The other type of macro events are application events, whenever the application starts (init) or shutdowns (destroy). Grails includes a BootStrap.groovy script inside your project’s configuration, from there you can typically setup initial data required by the application (DomainBuilder is really handy in this situation), conversely you may delete any data saved. Or you could trigger a webservice call, it doesn’t have to be database related, the point is that you can put there whatever your application requires.

He finalizes with the micro level events, those fired by domain classes whenever they come in contact with the database, those events are: beforeInsert, befortUpdate, beforeDelete, and onLoad. The names should be self-explanatory, still Scott gives a good example of their usage.

Events throughout Grails can help you further customize the way your application behaves. You can extend the build process without modifying the standard Grails scripts by creating an Events.groovy file in the scripts directory. You can customize the startup and shutdown process by adding your own code to the init and destroy closures in the BootStrap.groovy file. And finally, adding closures like beforeInsert and beforeUpdate to your domain class allows you to add behavior such as timestamping and geocoding.

Tags: ,

Mastering Grails: Grails and Legacy Databases (Scott Davis)

, , July 15th, 2008

Original Source

Scott Davis has delivered the next installment of his Mastering Grails series: Grails and Legacy Databases. On this article he discusses 3 different options offered by Grails to let you work with legacy databases. What good would be to the Java community a framework like Grails if in order to use it you must throw away existing working/legacy code?

The Grails Object Relational Mapping (GORM) API is one of the centerpieces of the Grails Web framework. In “GORM: Funny name, serious technology,” you were introduced to the basics of GORM, including simple one-to-many relationships. Later, in “Many-to-many relationships with a dollop of Ajax,” you used GORM to model increasingly sophisticated class relationships. Now you’ll see how the “ORM” in GORM has the flexibility to deal with table and column names in your legacy databases that don’t follow standard GORM naming conventions.

Scott begins with a sound advice: always backup your data. He then proceeds to show a pair of Groovy scripts tailored to backup/restore the particulars of the sample data used on the article’s application. The scripts skim the surface of what you can do with MarkupBuilder (Groovy to XML) and XMLParser (XML to Groovy), you will find plenty of information about them at the article’s Resources listing. He also notes

Remember that for relationships between tables to work, the primary-key field on the one side of the relationship must match up to the foreign-key field on the many side of the relationship. For example, the value stored in the id column in the airport table must be the same as the value in the arrival_airline_id column in the flight table.

To ensure that the autonumbered id fields get restored to the same value, be sure to drop all tables before you restore them. This resets the autonumbering back to 0 when Grails recreates the tables the next time it starts up.

Importing data to the legacy schema is also done via a Groovy script and XMLParser. Because of the nature of the particular data chosen for this application, namespaces must be taken into account. Again Groovy comes to the rescue, making the job much easier than with regular Java. Scott mentions a possible gotcha after reaching this step:

Now that your legacy table is in place, you should do one last thing: disable the dbCreate variable in grails-app/conf/DataSource.groovy. Recall from “GORM: Funny name, serious technology” that this variable instructs GORM to create the corresponding table behind the scenes if it doesn’t exist, and alter any existing tables to match the Grails domain classes. If you are dealing with legacy tables, you should disable this feature so that GORM won’t disrupt the schema that other applications might be expecting.

It would be nice if you could selectively enable dbCreate for certain tables and disable it for others. Unfortunately, it is a global “all or nothing” setting. In situations in which I have a mix of new and legacy tables, I allow GORM to create the new tables, then turn dbCreate off and import my existing, legacy tables. You can see how having a good backup-and-restore strategy is important in such situations.

On to the main course, Scott describes 3 different options to map legacy schemas to Grails domain classes

  1. Static mapping blocks - the Grails way, usually chosen when no legacy Java classes exist or when you want to start over.
  2. Legacy Java classes with HBM files - the compatible way for those that stayed away of EJB.
  3. EJB3 Annotations with Java classes - the painless EJB3/JPA option, configuration at a minimum.

Probably you have seen the first option before, as it is the simplest, groovier of the three. Similar to how constraints are declared in a regular Grails domain class, you must provide a static mappings closure that defines which table must be used and how columns are mapped to fields. The mapping DSL and the domain facilities are flexible enough, allowing you to define fields that must not be persisted for example.

The other two options are of special interest for developers already invested in either Hibernate or EJB3/JPA. Contrary of what you may think, the complexity of both options is almost non-existent. You just drop Java/HBM files in the correct places, add a shadow Groovy class for each domain class that defines the required constraints (remember that constraints are both used for data validation and view generation), tweak DataSource.groovy (in the case of the JPA annotated option) and that’s it. The article describes each option with full sample code.

Scott closes with the following statement

At this point, mapping your objects to relational databases in Grails should be a breeze. (That’s why they named it GORM, after all.) Once you feel confident that you can easily back up and restore your data, you have a variety of ways of getting Grails to conform to the nonstandard naming conventions in your legacy databases. The static mapping block is the easiest way to accomplish this task because it is the most Grails-like. But if you have legacy Java classes already mapped to your legacy database, there is no sense in reinventing the wheel. Whether you are using HBM files or the newer EJB3 annotations, Grails can take advantage of the work you’ve already done and allow you to move forward to other tasks.

Tags: , ,

Mastering Grails: Grails and the Mobile Web (Scott Davis)

, June 17th, 2008

Original Source

Scott Davis continues his Mastering Grails series with a new chapter: Grails and the Mobile Web. He writes at the introductory section:

These days, thankfully, it’s rare to see a Web site include the disclaimer "Best viewed using [Browser X]." Modern Ajax libraries such as Prototype, Dojo, and YUI do a reasonable job of abstracting away the remaining differences among Firefox, Internet Explorer, and Safari. But people visiting your Web site from a Nokia, Motorola, or Apple cell phone might not enjoy the same degree of browser independence. Even the latest mobile browsers that claim "full HTML support" can benefit from a few simple tweaks to the Web content. This article shows you how to optimize your Grails applications for mobile browsers.

If you’re wondering why you should even bother with making your Web site mobile-friendly, the numbers in the Mobile Web use on the rise sidebar might convince you. As impressive as the global statistics are, my interest in a mobile-friendly Web is more personal. I bought an iPhone when they first came out in summer 2007. Since then, I have been actively seeking out Web sites that are usable on the device. Sure, I can visit any Web site (as long as it doesn’t rely on Flash or Java™ applets, which the iPhone doesn’t support). The problem is that content optimized for 800×600 resolution (or higher) doesn’t look quite as nice on a 3.5-inch screen.

The Web sites I use regularly from my phone are the ones that meet me halfway with a UI that caters to the device’s unique constraints. Substituting an m for the traditional www in popular Web sites’ URLs is a good place to start. The pages at http://m.cnn.com, http://m.yahoo.com, and http://m.google.com all look good on my phone. Some Web sites, such as http://www.twitter.com, morph to the appropriate output magically: when I’m on a computer, I get all of the features; when I visit from my phone, the content is trimmed down and fits my screen like a glove. Same URL, optimized UI. I’ll show how your site can do these things too.

He then proceeds to explain some of the formats mobile devices will accept to display web content and how to produce content in said formats from your Grails enabled application. He even targets eye-candy gadgets as the iPhone. He finalizes the article by giving some advice to properly handle mobile clients without compromising your regular browser clients, mainly by

  • Creating a separate, dedicated Web site for mobile content
  • Sniffing the user agent
  • Sending back what the browser accepts

Probably some smart template management will also help to avoid file duplication, but that depends on your application needs.

As he points out at the beginning, mobile devices are everywhere, the number of connected devices increases as days go by. Given this accelerated rate and that there are more mobile/emebedded devices than computers out there, this article is a wake up call for those that want to stay in touch with customers in all ways possible, and what better way to do it by being productive with Grails at the same time.

Tags: ,

Ajax Development with the Yahoo! UI Library and Grails (Rich Web Experience)

, June 11th, 2008

Original Source

The Rich Web Experience has published a video, from a previous edition of the conference, where Scott Davis discusses integrating the Yahoo! UI Library and Grails to create a compelling user experience while remaining highly productive. Be aware that due to the nature of the presentation (multi-screen) some portions of the video do not display what Scott was showing at the moment.

You will have to follow the original link to actually see the video.

Please visit The Rich Web Experience website for more details on the conference, coming to both both sides of the Continental US this September.

About Scott Davis

Scott Davis Scott Davis is an internationally recognized author and speaker. He is passionate about open source solutions and agile development. He has worked on a variety of Java platforms, from J2EE to J2SE to J2ME (sometimes all on the same project).

Scott’s books include Groovy Recipes: Greasing the Wheels of Java , GIS for Web Developers: Adding Where to Your Web Applications , The Google Maps API , and JBoss At Work .

Scott is the Editor in Chief of aboutGroovy.com , a news and information website that tracks the latest developments in Groovy and Grails. He also writes a regular column for IBM DeveloperWorks — Mastering Grails .

Scott is a frequent presenter at national conferences (such as No Fluff, Just Stuff ) and local user groups. He was the president of the Denver Java Users Group in 2003 when it was voted one of the top-ten JUGs in North America. After a quick move north, he is currently active in the leadership of the Boulder Java Users Group . Keep up with him at http://www.davisworld.org .
More about Scott »

Tags: ,

Mastering Grails: Changing the view with Groovy Server Pages (Scott Davis)

, , March 11th, 2008

Groovy Server Pages (GSP) puts the Web in the Grails Web framework. In the third installment of his Mastering Grails series, Scott Davis shows you the ins and outs of working with GSP. See how easy it is to use Grails TagLibs, mix together partial fragments of GSPs, and customize the default templates for the automatically generated (scaffolded) views.

The first two articles in this series introduced you to the basic building blocks of the Grails Web framework. I’ve told you — repeatedly — that Grails is based on the Model-View-Controller (MVC) architectural pattern (see Resources), and that Grails favors convention over configuration for binding the framework’s parts together. Grails uses intuitively named files and directories to replace the older, more error-prone method of manually cataloguing these linkages in an external configuration file. For example, in the first article you saw that controllers have a Controller suffix and are stored in the grails-app/controller directory. In the second article, you learned that domain models can be found in the grails-app/domain directory.

This month, I’ll round out the MVC triptych with a discussion of Grails views. Views (as you might guess) are stored in the grails-app/views directory. But there’s much more to the view story than the intuitively obvious directory name. I’ll talk about Groovy Server Pages (GSP) and give you pointers to many alternative view options. You’ll learn about the standard Grails tag libraries (TagLibs) and find out how easy it is to create your own TagLib. You’ll see how to fight the ongoing battle for DRYness (see Resources) by factoring common fragments of GSP code into their own partial templates. Finally, you’ll learn how to tweak the default templates for scaffolded views, thereby balancing the convenience of automatically created views with the desire to move beyond a Grails application’s default look-and-feel.

– See Original @ DeveloperWorks (Scott Davis)

Tags: , ,

eWeek: Groovy Climbing Programmer Ranks (Darryl Taft)

, , , , February 22nd, 2008

Groovy is what Java would look like if it had been invented in the 21st century, said one developer.

RESTON, Va. – Groovy is getting its groove on and is moving up the charts.

At the 2G Groovy/Grails Experience conference here, Scott Davis, author of several books on Groovy, Java and editor in chief of aboutGroovy.com, said the Groovy language is moving fast up the charts of languages favored by developers.

Groovy now ranks 31 on the list of top programming languages, according to Davis and data from the TIOBE Software BV. Groovy had cracked the top 100 six months ago, moving from 103 to 52, and jumped to its current position in a January poll. Java remains the most popular programming language today, followed by the C language, Visual Basic, PHP, C++, Perl, Python and C#. Fortan, ColdFusion and ActionScript, also rank higher than Groovy.

Groovy, based on Java, is a dynamic language that runs on the Java Virtual Machine, or JVM. James Strachan, the creator of Groovy, first discussed the language on his blog in 2003, but early versions of the language did not appear until 2004, and a 1.0 release came out in January of 2007.

“Groovy is what Java would look like if it had been invented in the 21st century,” Davis said, noting that Groovy is “the next generation of Java.”

Davis, who delivered the opening keynote for the Groovy/Grails Experience, said people often ask whether Groovy will be a replacement for Java.

“It’s like saying do you think icing will ever replace cake,” Davis said. “It’s the same kind of relationship here. What we do is put a nice Groovy facade over Java things like icing over a cake.”

Davis said there is a symbiotic relationship between Groovy and Java. And that makes all the difference between Groovy and other dynamic languages that run on the JVM, he said.

“There’s JRuby out there,” Davis said. JRuby is an implementation of Ruby that runs on the JVM.

“JRuby is a great dynamic language if you already know Ruby,” Davis said. “And Jython is a great dynamic language if you know Python. But when you run JRuby on the JVM you’ve got this weird kind of disconnect.”

However, “Groovy is targeted at us: Java developers,” Davis said. “It is for us by us.”

Moreover, “because of the linguistic similarities between Java and Groovy it’s painless for developers to switch between Java and Groovy,” Davis said.

To implement Groovy, all a Java developer needs to do is “add a single JAR (Java Archive file) to your classpath; you don’t have to rewrite a single line of code,” Davis said.

Groovy runs on Java 1.4, 1.5 or 1.6.

Meanwhile, Grails is a Web application framework based on Groovy that is patterned after Ruby on Rails. Grails co-creator Graeme Rocher said Grails 1.0 shipped earlier this month. Rocher is the project lead for the open-source Grails project.

“Grails is a fully integrated, modern Java Web application in a box,” Davis said.

Grails includes support for Asynchronous JavaScript and AJAX frameworks.

“The plug-in system is really where the strength of Grails comes from,” Davis said. “Grails is a simple core, but it’s infinitely extensible through its plug-in system.”

Salil Deshpande, a partner at Bay Partners, a venture capital firm, said, “what’s cool about Groovy is it’s basically a language that is very Ruby-like, but it’s a superset of Java.”

Further, Deshpande explained that because Groovy is based on Java then “enterprises can preserve their legacy investments in Java” to extend their development to a dynamic language or lightweight Web development framework such as Grails.

“For the six to nine million Java developers out there, it’s easier for these guys to go to Groovy and Grails instead of Ruby and Rails,” Deshpande said.

Indeed, Matthew Porter, founder of Contegix, a managed hosting firm, said Contegix went to Groovy and Grails for several reasons, including being able to use their existing skill set in enterprise Java.

Darryl Taft, eWEEK

Tags: , , , ,