My Favorite Grails Plugins (Scott Walter)

, March 15th, 2008

One of the most powerful features of Grails is their plugin system. Using a simple command “grails install-plugin” you can increase the functionality of your application. Sweetness! The core Grails developers didn’t think lightly on plugins, they have a great API to use when you want to write your own plugin.

Here are some of the plugins that I will be using on Siteproducer:

1. Acegi - The Acegi security system is a very comprehensive security system, but sometimes it requires too much configuration.   Following the Grails paradigm “convention over poker browser gamewingows poker bonusparty poker gamespoker spielen um sonstholdem poker regelnpoker bonus 1000strip poker pc spieldeutsches online pokerfive draw pokerlan poker spielstrip poker full gamepoker texas holdem regelntexas holdem poker spiel downloadonline poker browseronline poker umsonstsiti poker onlinedraw poker on linegambling pokerstrip poker download gratisvincere poker onlinegiochare omaha poker in lineadownload gioco pokerchips di pokerstrp pokerpoker online italiagiochi omaha pokerdownload gioco poker gratisgioco poker onlinevc pokersrtip poker gratispoker multiplayer online,poker online,holdem poker onlineregole poker omahaitalian pokerregolamento gioco pokerpoker room on linepoker scaricabili gratisgioco poker da scaricareguida poker onlinestrep poker gratistexas holdem softwarepoker in linea gratis,poker in linea,poker lineastrip poker pccaribbean pokerstanze da pokerstrategie texas holdempoker da giocarepoker sportivo onlinedownload live pokerholdem poker downloadpoker texas gratis configuration” the Acgei plugin will setup Acegi with very little effort on your part.   The plugin gives you:  login controller, logout controller, registration controller, and crud pages to manage protected resources.  You will be up and running with a secure Grails application in about 5 minutes.

2.  Acts As Taggable - Tagging is all the rage these days and the acts as taggable brings tagging to your domain objects.   The plugin is super simple to use, just add “implements Taggable” to your domain objects and that’s it.   Acts As Taggable exposes methods to add tags, delete tags, and list tags on your domain object.

3.  Quartz - Quartz the practically standard mechanism for performing scheduled tasks has made its way to a Grails plugin (it use to be part of Grails core).  Once you have the plugin installed you can easily do scheduled tasks like this:
class FirstJob {
def cronExpression = "0 0 0 ? * *" //midnight, every day

def execute() {
log.info("firstjob executed")
}
}

4.  Searchable - The searchable plugin is a huge time saver!  Searchable adds full-text searching of your domain objects via Lucene and Compass.   One nice thing about the plugin is that you don’t have to know a lick about Lucene or Compass and still get all the benefits.   The plugin also supports relationships between your domain objects.  To get your started there is even a bundled search controller so you can verify that when you save your domain objects they are being properly indexed.

5.  WebTest - Unit and Integration testing is great.  But how about testing from end-to-end from the end-users perspective?   WebTest is a great functional testing tool and the Grails plugin for WebTest makes it super simple to create and execute your functional tests.

There are alot more plugins available for your Grails applications.   Feel free to take a look at them at grails.org/plugins.

Scott Walter

Tags: ,

Nothing Makes You Want Groovy More Than XML (Ken Kousen)

, March 12th, 2008

I’m in Delaware this week teaching a course in Java Web Services using RAD7. The materials include a chapter on basic XML parsing using Java. An exercise at the end of the chapter presented the students with a trivial XML file, similar to:


<library>
  <book isbn="1932394842">
    <title>Groovy in Action</title>
    <author>Dierk Koenig</author>
  </book>
  <book isbn="1590597583">
    <title>Definitive Guide to Grails</title>
    <author>Graeme Rocher</author>
  </book>
  <book isbn="0978739299">
    <title>Groovy Recipes</title>
    <author>Scott Davis</author>
  </book>
</library>

(with different books, of course) and asked the students to find a book with a particular isbn number and print it’s title and author values.

I sighed and went to work, producing a solution roughly like this:


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ParseLibrary {
    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document doc = null;
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse("books.xml");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        NodeList books = doc.getElementsByTagName("book");
        for (int i = 0; i < books.getLength(); i++) {
            Element book = (Element) books.item(i);
            if (book.getAttribute("isbn").equals("1932394842")) {
                NodeList children = book.getChildNodes();
                for (int j = 0; j < children.getLength(); j++) {
                    Node child = children.item(j);
                    if (child.getNodeType() == Node.ELEMENT_NODE) {
                        if (child.getNodeName().equals("title")) {
                            System.out.println("Title: "
                                + child.getFirstChild().getNodeValue());
                        } else if (child.getNodeName().equals("author")) {
                            System.out.println("Author: "
                                + child.getFirstChild().getNodeValue());
                        }
                    }
                }
            }
        }
    }
}

The materials didn’t supply a DTD, so I didn’t have any ID attributes to make it easier to get to the book I wanted. That meant I was reduced to continually using getElementsByTagName(String). I certainly didn’t want to traverse the tree, what with all those whitespace nodes containing the carriage-return/line-feed characters. So I found the book nodes, cast them to Element (because only Elements have attributes), found the book I wanted, got all of its children, found the title and author child elements, then grabbed their text values, remembering to go to the element’s first child before doing so.

What an unsightly mess. The only way to simplify it significantly would be to use a 3rd partly library, which the students didn’t have, and it would still be pretty ugly.

One of the students said, “I kept waiting for you to say, ‘this is the hard way, now for the easy way,’ but you never did.”

I couldn’t resist replying, “well, if I had Groovy available, the whole program reduces to:


def library = new XmlSlurper().parse('books.xml')
def book = library.books.find { it.@isbn == '1932394842' }
println "Title: ${book.title}\nAuthor: ${book.author}"

“and I could probably shorted that if I thought about it. How’s that for easy?”

On the bright side, as a result I may have sold another Groovy course. :) For all of Groovy’s advantages over raw Java (and I keep finding more all the time), nothing sells it to Java developers like dealing with XML.

 

Ken Kousen

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: , ,

Grails vs. Rails (Matt Raible)

, March 7th, 2008

In a comment, Jared Peterson asked:

I’m curious if you have any thoughts on folks that might be trying to make a decision between Rails and Grails. I like the concept of “Allow Both”, but what if you “have neither”?

If you were starting a new project, could choose either one, needed to interact with a lot of existing Java code (JRuby on Rails I guess), what would you pick?

A friend recently asked me “Can I solicit your honest, unadulterated opinion on Grails?” I think the e-mail I sent him may help Jared’s question.

I think it’s awesome. IMO, it’s the same thing as AppFuse, but it has a DSL that’s much simpler to learn and remember. Less code -> faster productivity. There does seem to be some maturity issues, but I think it’ll get there. The question is - how fast can Groovy become. It’s similar to Rails and Ruby in that you start using Grails and you think “This Groovy thing is kinda cool, I’d like to learn more.” One of the reasons I really like it is the learning curve for experienced open source Java Developers is virtually flat. You can learn enough to be productive in a single day.

That being said, I think there’s also a lot of cool stuff going on with RIA. IMO, Flex or GWT + Grails would be a really fun set of tools to develop with. Here’s a excerpt from a write-up I recently did when analyzing Rails and Grails at LinkedIn (in January):

——–
Comparing Rails and Grails
They’re both excellent frameworks. Rails is definitely more mature, but the environment is a pain to setup (esp. on Windows). Grails is very easy to setup for Java Developers. Grails needs a lot of improvement as far as hot deploy and stack traces. It’s probably Groovy’s fault, but its stack traces are hideous - rarely pointing to the class and line number in the first few lines.

As for hot deploy, it doesn’t work nearly as well as it does with Rails. Rails’ “script/server” starts WEBrick in a few seconds, while “grails run-app” can take up to 10 seconds (even on a brand new application). Even with its warts, Grails is simply awesome. I really, really enjoy writing Groovy code in IDEA and seeing immediate changes. I don’t like “test-app” as much as I like Rails’ “test:units” (or even better, “test:uncommitted”). It seems to be widely realized that Rails has a better testing story.

Rails is immediate, Grails is immediate 70% of the time.

Groovy is extremely easy to learn for Java Developers. Ruby is easy too learn, and possibly too powerful for OO rookies. Both are fun to program in and very capable of allowing greater developer productivity. If you know Hibernate, Spring, SiteMesh and JSP, you owe it to yourself to look at Grails. If you know these technologies well, you can learn Grails in less than an hour. You can be productive in the next hour and have an application running by the end of the day. That’s not to take anything away from Ruby. I believe that Rails is an excellent platform as well. It’s pretty cool that profiling and benchmarking are built into the framework and you can easily judge how many servers you’ll need to scale.

I used IDEA while developing with both frameworks. IDEA has Rails and Groovy support available via plugins and they both worked quite well. The support for Grails was much better than Rails. Grails offers code completion, Ctrl+click on classes/methods, debugging and starting/ stopping the webapp from your IDE. Rails doesn’t offer much in the way of Ctrl+clicking on class names/methods or debugging.
——–
Is there anything that Rails can do that Grails can’t? Not as far as I can tell. I think it really comes down to developer passion and team preference. If you have experienced Java Developers that like the ecosystem and its tools, Grails makes a lot of sense. If you have experienced PHP developers or frustrated J2EE developers, they might enjoy Rails more. One thing that’s very cool about both frameworks - learning one actually teaches you things about the other. They’re so similar in many respects that knowledge is transferable between the two.

Of course, this is all just my opinion after working with both frameworks for a few weeks. For anyone who has tried both, what do you think?

In closing, here’s an excerpt from a recent comment I left on Javalobby:

Of course, the hard part now is deciding between Django, Rails, Grails and GWT for your web framework. Then again, that’s like having to choose between a Ferrari, Porsche, Lamborghini and a Maserati. No matter which one you choose, it’s unlikely you’ll be disappointed.

Matt Raible

Tags: ,

Grails: The LinkedIn Journey Continues (Matt Raible)

, March 6th, 2008

As you might know, I’ve spent the last several months working for one of the coolest clients ever: LinkedIn. They hired me back in July 2007 and I was impressed on day one. I was originally hired to help them evaluate open source Java web frameworks and try to determine if moving from their proprietary one to an open source one would help improve developer productivity.After looking at all the options, I recommended we look at Struts 2 and Spring MVC - primarily because they seemed to be the best frameworks for a LinkedIn-type of application. Another Engineer and I prototyped with Struts 2 for about 6 weeks and came up with a prototype that worked quite well. While our mission was successful, we found a couple issues with Struts 2 and standard JSP that might actually hurt developer productivity more than it helped.

Following this project, I worked on the New Homepage Team, which is now visible to everyone that logs onto LinkedIn. My role was minimal, but it was still a very fun project to work on. You know those widgets in the right panel? I did the initial UI and backend integration for those. All the business logic, Ajax/JavaScript, CSS, and optimization was done by other folks on the team. Shortly after this project went live in November, I started prototyping again with Spring MVC + JSP.

The reason I was asked to prototype with Spring MVC was because they were using Spring on the backend, Spring MVC in a couple other projects, and a new project was being kicked off that used Grails. Rather than add another framework (Struts 2) to the mix, they wanted to see if they could suppress any further framework proliferation.

After a month of prototyping with Spring MVC + JSP, my results weren’t as good as Struts 2. With Struts 2, I was able to use OGNL to do all the things their current JSP implementation allows them to do (call methods with arguments, use statics in EL, etc.). With standard JSP, a lot of this wasn’t possible. If it was - it required writing lots of tag libraries and made it more cumbersome for developers to do certain things. At the end of that project, I determined that using FreeMarker might solve these problems. I also determined that neither Struts 2 nor Spring MVC would solve the ultimate problem of developer productivity. Neither framework would allow developers to go from make-a-change-and-deploy, wait-3-minutes-to-see-change-in-browser to make-a-change, save and wait-15-seconds-to-see-change-in-browser.

I recommended that this be the ultimate goal - to get rid of the deployment cycle and to allow minimal turnaround when deploying modified classes. After that problem was solved, it’s true that moving to an open source web framework would likely provide an easier-to-remember API. However, the problem with moving to a new web framework would be that everything used to construct the existing site would suddenly become legacy code.

In the end, we concluded that the best solution might be to enhance the existing framework to be more like the available open source options. This would allow existing applications to keep using their code — and if we enhance properly — new applications can use a simpler, less verbose API and a templating framework that’s easier to understand. We can make LinkedIn’s version of JSP more like standard JSP while allowing its powerful EL to remain. We can add support for JSP Tag Libraries and Tag Files.

One of the benefits of moving to an open source web framework is there’s a community, documentation and books that describe the best (or most common) ways to solve problems with the framework. LinkedIn has this, but it’s all in code and no one seems to have a high-level of confidence that the way that they did it is the “best” way. Developers communicate well, but all the knowledge is stuck in their heads and inboxes - there’s no way for new developers to search this knowledge and figure it out on their own without asking somebody.

By adopting an open source web framework, it’s possible to solve part of this problem, but I think it’s still going to exist - where a few engineers know how to use the framework really well (for the specific application) and the rest don’t. We determined that regardless of open source vs. proprietary framework, what was needed was a set of developers that acted as authorities on how to develop web applications at LinkedIn. A UI Frameworks Team if you will. This would be their only job and they would never get pulled from this to work on projects or complete tasks related to LinkedIn’s products. Some developers mentioned that they’d been asking for this for years, and some folks had even been hired for this. However, the formulation of this group has never happened and it’s obvious (now more than ever) that it’d be awesome to have them.

The UI Frameworks Team
At the end of 6 months, it seemed my work was done at LinkedIn. I liked the idea of a UI Frameworks Team and recommended they start it with the authors of the existing web framework. They agreed this was a good idea. A few days later, I was pulled into the CTO’s office and he offered me the job. He offered me the challenge of building this team and told me I could do it remotely (from Denver) and hire my own people to help me with it. I gulped as I realized I’d just been offered the opportunity of a lifetime. I knew that while this might not be the best option for LinkedIn, it certainly was an excellent opportunity for me. I said I’d think about it.

In the meantime, I was given a project which you might’ve read about. They asked me to migrate a Rails application to Grails and try to determine if they really needed both frameworks. I spent 2 weeks coming up to speed on both and flew to Mountain View to deliver my conclusion. Here’s an excerpt from an internal blog post I wrote.

As far as I know, Rails has been used at LinkedIn for well over 6 months and Grails has been used for a similar duration. Both projects that’ve used these technologies have enjoyed extreme success. Both projects have been fun for the developers working on them and both have improved the technologies/frameworks they’re using.

Here’s an interesting quote about the Rails application:

Another app you might want to look at is BumperSticker, our facebook app. Interestingly we heard through joyent that DHH (the creator of Rails) told them that BumperSticker is the biggest rails app in the world (in terms of page views) - we are closing in on 1 billion monthly page views and we have 1 million unique users per day (about 10 million installs on FB). It’s a little trickier to setup in a dev environment since you need to be running on FB, but the code itself is pretty interesting since we’ve iterated on it a bunch of times and are making extensive use of third party libraries such as memcached.

This quote loosely translates to “We have some Rails Ninjas on staff and we’ve been quite successful in developing with it and making it scale”.

Both platforms have allowed developers to iterate quickly and turbo-charge their productivity.

My Conclusion: Allow Both

Why?

If you have talented developers that can whip out kick-ass code with either platform, pay them and pay them well. Passion is the most important part of any job. If developers are passionate about the application they’re developing and the language they’re using (notice language is secondary) - they can do great things.

I know this probably isn’t the answer you wanted to hear, but it’s what I believe. I think both frameworks are very similar. I believe the knowledge you gain from learning one framework is transferable to the other. A lot of the things I learned about Rails worked with Grails. Ruby’s syntax is similar to Groovy’s.

There’s a natural synergy between these two frameworks. The hard part is figuring out when to use which one.

The application that I was asked to port from Rails to Grails? The one that was launched last week - LinkedIn Mobile.

After doing this research, I stepped up to the plate and accepted the offer to start a UI Frameworks Team and recruited some kick-ass Java Developers I know to be the founding members. Last week, I flew out to Mountain View to do some kickoff meetings and start getting the infrastructure in place so we can document, support and release code like a well-oiled open source project. There’s nothing saying we won’t use an open source web framework as the underlying engine, but I think this should be an excellent chance to see the power of open source governance and development style in a corporate environment.

Director of Engineering, Core Experience
I should mention one last thing. If you’re an experienced Java Developer/Architect with a passion and deep knowledge of UI development (JavaScript, CSS, HTML), we’ve got a Director of Engineering, Core Experience position with your name on it. I might even get to interview you if you apply for this job. Furthermore, whoever gets hired will likely work very closely with my team. What’s not to like about that!?

Matt Raible

;-)

Tags: ,

Grails Is a Developer’s Dream (Ganesh Prasad)

, March 5th, 2008

The next session I attended was by a person from Atlassian. This session was on Grails. Now, I’d heard of Grails, but didn’t quite know what it was all about. I assumed it was a very different technology from Java, something like Ruby on Rails. Only half right, as it turned out. Yes, the technology was inspired by Ruby on Rails, but it’s based on Java technology. To be precise, it’s a software stack consisting of Java, Groovy, Spring, Hibernate and HSQLDB.

It’s a little hard to describe what Grails is. Those who attended Ben Alex’s talk early last year on the coming Spring project tentatively called ROO (Real Object Oriented) will have a fair idea of what I’m talking about. Grails seems to have everything that ROO promised (but hasn’t yet delivered on). It’s a toolset that lets designers build applications based on the principles of Eric Evans’s Domain-Driven Design, and it works very hard behind the scenes to build all the infrastructure required to make the domain objects just work. Persistence, a RESTful web interface, test cases, - all get automatically generated. An increasingly common theme that I’m hearing pervades Grails - “Convention over configuration.” In other words, if you stick to standard naming conventions for things that you create, the system will make it very easy for you to build a working application with a minimum of coding.

That’s the jaw-dropping technology I talked about at the beginning of this post. Grails is a developer’s dream. One can knock together working code in minutes. InfoQ has a Grails guide and example code which I intend to work through as soon as I possibly can. I would recommend Grails to all Java developers looking for the next burst of productivity. Best of all, Grails applications can be exported into standard war files and run on standard app servers, so there is no need for any new run-time technology.

Funny how one can be searching for months for a productive development environment that lets you build applications rapidly yet correctly, and then one fine day, it comes up and hits you between the eyes. Praise the Lord! I intend to use Grails to illustrate concepts with working code from now on. I’ll blog about my experiences with Grails as I get some experience with it.

Ganesh Prasad

Tags: ,

Plug-in: Migrating from Struts to Grails (Graeme Rocher)

, March 4th, 2008

Grails is a full stack framework that provides everything from the build system to the persistence layer. Struts 1 is a first generation Java web framework that is still very popular, but it only solves the controller/view layer.

This plug-in allows you to use Struts 1 as a the controller/view layer for Grails and also provides a migration path to Grails from Struts 1.

Getting Started

Once you have created a Grails application, you need to install the plug-in. The plug-in is hosted in the Grails central repository and can be installed with:

grails install-plugin struts1

Alternatively you can download the plugin as a zip file from here: http://svn.codehaus.org/grails-plugins/grails-struts1/tags/LATEST_RELEASE/

And then run

grails install-plugin /path/to/file/grails-struts1-1.3.8.zip

Either way it will set up struts with the most common servlet mapping of *.do. The next thing you need to do is change the way Grails deals with file extensions otherwise Grails will swallow the *.do mapping. To do this set the following property in grails-app/conf/Config.groovy:

grails.mime.file.extensions = false

Now you have setup Struts 1 inside Grails and there is a struts-config.xml and validation.xml within /web-app/WEB-INF. Now when you run

grails run-app

Struts will load inside Grails

Example Application

You can download an example of the Struts mailreader application runing inside Grails.

Migrating an Existing Struts application

To migrate an existing Struts 1 application you can simply:

  1. Copy your struts-config.xml and validation.xml into web-app/WEB-INF overriting the existing ones if necessary
  2. Copy Java sources into src/java
  3. Copy all dependant JAR files into the lib directory

Forwarding to a GSP view from Struts

You’ll notice that by default the struts-config.xml setup by Grails has the following mapping:

<action
            path=“/Welcome”
            forward=“/index.gsp”/>

Notice how we’re able to map the URI /Welcome.do to a GSP page.

Mapping a Struts action to a Grails controller

If you prefer to write your controller logic in Grails controller you can do so and use the ControllerActionProxy class to map to it. For example given the following Grails controller:

class TestController {
	def foo = {
		println “EXECUTING FOO”
	}
}

To map to this controller with ControllerActionProxy simply add this to struts-config.xml:

<action
            path=“/test/foo”
            type=“org.codehaus.grails.struts.action.ControllerActionProxy”
            />

Now when you go to /test/foo.do in the browser the ControllerActionProxy will automatically map onto the Grails controller.

Even better Grails’ view mapping conventions will be honoured and in this case the view grails-app/views/test/foo.gsp will be rendered.

The Struts 1 plug-in also adds two new implicit properties to the Grails controllers:

  • actionForm - An instance of the Struts ActionForm class if one is configured for the Action

Graeme Rocher (Original)

Tags: ,