Introducing Spring Roo, Part 1: Building from source

Spring Roo is a lightweight productivity tool for Java™ technology that makes it fast and easy to develop Spring-based applications. Applications created using Spring Roo follow Spring best practices and are based on standards such as JPA, Bean Validation (JSR-303), and Dependency Injection (JSR-330). Roo offers a usable, context-aware, tab-completing shell for building applications. Spring Roo is extensible and allows add-ons, enhancing its capability. This article introduces Spring Roo and provides step-by-step instructions on building Spring Roo source on Windows® and *nix systems.

Share:

Shekhar Gulati, Senior Consultant, Xebia

Shekhar Gulati is a Java consultant working with Xebia India. He has six years of enterprise Java experience. He has extensive experience in Spring portfolio projects, such as Spring, Spring-WS, and Spring Roo. His interests are Spring, NoSQL databases, Hadoop, RAD frameworks like Spring Roo, cloud computing (mainly PaaS services like Google App Engine, CloudFoundry, OpenShift), Hadoop. He is an active writer and writes for JavaLobby, Developer.com, IBM developerWorks and his own blog at http://whyjava.wordpress.com/. You can follow him on twitter @ http://twitter.com/#!/shekhargulati.



10 April 2012 (First published 25 January 2011)

Also available in Russian Japanese Vietnamese Portuguese

Introduction

The Spring framework was released in late 2002 to simplify J2EE (now JavaEE) development. Over the past eight years, Spring has successfully accomplished this mission by giving the Java community frameworks or features like Spring Security, Spring MVC, transaction management, Spring batch, and Spring integration, which are easier to understand and use. Spring wanted to make a Java developer's life even easier and more productive. To make this happen, Spring created a development tool called Spring Roo.

Spring Roo (see Resources) is an extensible, text-based open source RAD tool for Java technology. It is a powerful resource for creating and managing Spring-based applications. Here is the mission statement:

Roo's mission is to fundamentally and sustainably improve Java developer productivity without compromising engineering integrity or flexibility.

This quest translated into a tool built on Java technology, which sustainably increases productivity over the full life cycle of a project and does not lock developers into a particular approach. Spring Roo uses popular, proven, and mature libraries such as Spring framework, Java Persistence API, Java Server Pages (JSP), Spring Security, Spring Web Flow, Log4J, and Maven. The applications generated by Roo use standards like Bean Validation (JSR-303) and Dependency Injection (JSR-330), and follow best-practice SpringSource-certified application architecture.

Using Spring Roo, you can add and configure features such as JPA, Spring MVC, Spring Security, Logging using Log4j, testing frameworks like JUnit and Selenium, Solr, JMS, email, and many more, by simply typing commands on the Roo shell. The time saved using Roo to add these features increases developer productivity. Roo can't write business logic, but it can manage infrastructure or the configuration of an application.

Roo is a development-time tool, which means an application is independent of Roo at runtime. As Roo does not exist at runtime, it does not have any performance or memory overhead. This ensures that you are not tied to Spring Roo, and you can remove Roo from your project at any time in a few keystrokes.

This article discusses building a simple web application using Roo shell and demonstrates how to build the Spring Roo source code on Windows or Ubuntu machines.


Getting started with Roo shell

You can manage and configure an application by loading the Roo shell and interacting with it using commands. Roo Shell is a tab-completing, context-aware, hint-providing command shell. You can use the hint command to ask Spring Roo about your next logical action. Roo is intelligent enough to suggest the next action by determining the context of your application. For example, let's say you have created an entity using the entity command. You then type the hint command. Roo will tell you that you should add fields to your entity using field. This feature reduces the conceptual weight of Roo and makes it an excellent learning tool. You can create the full application following Roo help and hint commands without ever referring to its documentation.

Prerequisites

Before you start working with Roo, make sure you have following installed:

  1. Java V6 JDK
  2. Apache Maven V2.0.9 or above

Installing Spring Roo

To install stand-alone Spring Roo:

  1. You can download Roo stand-alone command-line shell or use the built-in Roo SpringSource Tool Suite (STS) plug-in. I would suggest downloading both and using them together because STS offers many additional features over Eclipse for Spring-based applications.
    1. Spring Roo
    2. SpringSource Tool Suite
  2. Unzip Spring Roo to the location of your choice.
  3. Set the environment variable:
    1. On a Windows machine, add %ROO_HOME% /bin to the path where ROO_HOME is the path to the unzipped Roo files.
    2. On a *nix machine, create a symbolic link to $ROO_HOME/bin/roo.sh

      (e.g., sudo ln -s ~/spring-roo-1.x.x/bin/roo.sh /usr/bin/roo)

Building an application

To show you the power of Roo, let's create a simple enterprise conference application. A conference application has two entities: Speaker and Talk. A Speaker can give one or more talks, and Talk will be given by only one speaker. The simple class diagram is shown in Figure 1.

Figure 1. Class Diagram Speaker Talk
Diagram that shows elements for Speaker (firstName, lastName, etc.) are associated with Talk elements (title and description)

Create the application:

  1. Open your operating system command-line shell.
  2. Create a directory named conference using the mkdir command.
  3. Go to the conference directory in your shell.
  4. Type roo. This command will initiate the Roo shell as shown in Listing 1.
Listing 1. Starting the Roo shell
C:\Users\xebia\demo\conference>roo
    ____  ____  ____
   / __ \/ __ \/ __ \
  / /_/ / / / / / / /
 / _, _/ /_/ / /_/ /
/_/ |_|\____/\____/       1.1.B.RELEASE [rev 793f2b0]
Welcome to Spring Roo. For assistance press TAB or type "hint" then hit ENTER.
roo>

Now that we are inside the Roo shell, we will use Roo's hint command to guide us through the next steps. hint suggests creating a new Maven-based Spring project using project (see Listing 2).

Listing 2. Using hint in the Roo shell
Welcome to Spring Roo. For assistance press TAB or type "hint" then hit ENTER.
roo> hint
Welcome to Roo! We hope you enjoy your stay!
Before you can use many features of Roo, you need to start a new project.

To do this, type ’project’ (without the quotes) and then hit TAB.

Enter a --topLevelPackage like ’com.mycompany.projectname’ (no quotes).
When you're finished completing your --topLevelPackage, press ENTER.
Your new project will then be created in the current working directory.

Note that Roo frequently allows the use of TAB, so press TAB regularly.
Once your project is created, type ’hint’ and ENTER for the next suggestion.
You're also welcome to visit http://forum.springframework.org`for Roo help.
roo>

As suggested by the hint command, we will create a project using the project command. This command has one required attribute, topLevelPackage, to specify the name of the root package. In addition to the required attribute, we will use two optional attributes: java (to specify the Java version) and projectName (to specify the name of the project). Type the following:

	project --topLevelPackage com.dw.roo.conference --java 6 --projectName conference

This command will create a Maven V2-managed Spring-based project as shown in the following output:

	Created C:\Users\xebia\demo\conference\pom.xml
	Created SRC_MAIN_JAVA
	Created SRC_MAIN_RESOURCES
	Created SRC_TEST_JAVA
	Created SRC_TEST_RESOURCES
	Created SRC_MAIN_WEBAPP
	Created SRC_MAIN_RESOURCES\META-INF\spring
	Created SRC_MAIN_RESOURCES\META-INF\spring\applicationContext.xml
	Created SRC_MAIN_RESOURCES\log4j.properties

Again, type hint to ask Roo for the next action. This time it suggests setting up the persistence mechanism. Type persistence setup on the shell and press Tab three times. You will obtain options for --provider. Press H and then Tab to complete "HIBERNATE". After the provider, press tab for database choices, and you will see a number of options. Because we are using Hibernate as our provider, we cannot choose a non-relational database like Google App Engine. For now, we are going to use the HYPERSONIC_IN_MEMORY database.

	persistence setup --provider HIBERNATE --database HYPERSONIC_IN_MEMORY

There are other optional attributes, such as username and password, which we don't need at this time.

Now that we have set up the persistence mechanism, we will again utilize the hint command. This time we're told to create entities using the entity command. Entity is used to create the actual domain objects and has one required attribute, class, to specify the name of the entity. In addition to the required --class attribute, we will use the --testAutomatically attribute, which creates integration tests for a domain object. Let's create two entities: Speaker and Talk.

	entity --class ~.domain.Speaker –testAutomatically
	
	entity --class ~.domain.Talk --testAutomatically

I have used ~ as a placeholder for project top-level package.

Entity will create a flexible, feature-rich JPA entity. The created entities will have JPA @Entity with ID, version, EntityManager, and a no-argument constructor. The generated entity will have methods such as persist, merge, remove, flush, count, find, and findById, etc. If you look at the output of this command, you will notice that this command, in addition to creating Java files (for Speaker and Talk), also created AspectJ files ending with *Roo_*.aj. These *Roo_*.aj are called Intertype Declaration (ITD), Mixins, or Introductions. Roo uses ITD as a code-generation artifact. ITDs allows Roo to generate code in a separate compilation unit, but ITDs are combined into the same compiled class at compilation time. AspectJ intertype declarations are used to automatically generate ID and version fields, and getters and setters for persistence fields in domain classes.

Using hint again provides the suggestion to add fields to the entity using the field command. Let's add some fields to the Speaker entity:

	field string --fieldName firstname --class ~.domain.Speaker --notNull 
	field string --fieldName lastname --notNull 
	field string --fieldName email --unique --notNull 
	field string --fieldName organization 
	field date --fieldName birthdate --type java.util.Date --past --notNull 
	field number --type java.lang.Long --fieldName age --min 25 --max 60

--class options let us specify which class we want to add fields to.

The field command can be used to specify JavaBean validation-specific annotations with options such as --max and --min, etc. It can also be used to specify JPA-specific annotations with options like --fetch, --column, and --unique, etc. For date fields, you can also specify whether the date should be past or future as used above. Using field, you don't have to remember these annotations.

Now let's add some fields to the Talk entity:

	field string --fieldName title --class ~.domain.Talk --notNull 
	field string --fieldName description --notNull --sizeMax 4000

So far, we have created the entities and added fields to them, but we have not specified the relationship between them. The relationship between Speaker and Talk is ONE_TO_MANY (i.e., one speaker can give any number of talks). This is done using field, as shown below:

	field set --fieldName talks --type ~.domain.Talk --class \
~.domain.Speaker --cardinality ONE_TO_MANY
	
	field reference --fieldName speaker --type ~.domain.Speaker \
--class ~.domain.Talk –-notNull

Now we will want to scaffold a web tier for conference application. This is done using the controller command. The most convenient way to generate controllers and all relevant web artifacts is to use controller all.

	controller all --package ~.web

The first use of the controller command will also add additional dependencies, such as Spring MVC and Tiles to your project. This might take some time to run as it has to download all the dependencies (if they don't exist in your Maven repository). This command also shows one of the features of Roo: that it adds dependencies only when they are needed.

Next, we will set up the log4j using logging command:

	logging setup --level INFO --package ALL_SPRING

The last thing we should do before quitting the Roo shell is run the integration tests that were generated when we specified --testAutomatically with the entity command. To run the tests from within the shell, type perform tests.

Roo delegates the call to Maven to run the tests, so therefore, perform tests is equivalent to a mvn test command. Quit the shell by typing q or quit.

These commands will create a fully functional conference application. Next we will run this application.

To run the application, type mvn tomcat:run which will start the jetty server. Open a web browser and go to http://localhost:8080/conference/. You will see the screen shown in Figure 2.

Figure 2. Conference application home page
Screenshot of the the conference application in a browser with the menu items down the left side and the content on the right

You can click Create new Speaker to create a conference speaker. You can also view, edit, and delete a user by clicking List all Speakers. In the same way, you can create a Talk, but not before a Speaker is created.

This is a simple application, but it shows how easily you can create a new Spring-based web application from scratch in minutes. In the second part of this series, I will show you how to build an application using different Roo features and add-ons.

Now that we have created a simple application, I will show how you can build the Spring Roo source on Windows and Ubuntu.


Building Spring Roo from source

Spring Roo V1.1.0 is the latest production release version, and active development is happening under the V1.1.1 release. There are reasons why you might require building Spring Roo from source:

  1. Spring Roo does not provide nightly builds, so if you want the latest features of Spring Roo you need to build the source of Spring Roo.
  2. You want to do any sort of development for the Spring Roo project.
  3. You want to write an add-on for Spring Roo.
  4. You just want to play around with Spring Roo code to see how it is implemented or written.

Outcome

By the end of this section, you will be able to run a successful Maven build of the latest Spring Roo source code on both Windows and *nix systems. You will be able to work with the latest Spring Roo and be able to import the Spring Roo projects in Eclipse or STS (SpringSource Tool Suite).

Process for building Spring Roo source on Ubuntu

Building source code on Ubuntu (and other *nix systems) is easy. Simply follow these steps:

  1. Install Git, a distributed source code-control management system. To install it on your Ubuntu system, type sudo apt-get install git-core gitk.
  2. Checkout Spring Roo using Git by typing git clone git://git.springsource.org/roo/roo.git. You will see a roo folder in your home directory containing all of the Roo source code.
  3. GnuPG allows encrypting and signing your data and communication, and features a versatile key-management system and access modules for all kinds of public key directories. Roo uses GPG to automatically sign build outputs.
  4. Fire the command gpg --list-secret-keys. The output should appear similar to Listing 3.
    Listing 3. Result of gpg list command
    C:\dev\roo-sourcecode\roo>gpg --1ist-secret-keys
    C:/Users/xebia/AppData/Roaming/gnupg\secring.gpg
    sec 2048R/2F96093B 2010-07-03
    uid                shekhar (spring-roo) <shekhargu1ati84@gmai1.com>
    ssb 2048R/B77E5C63 2010-07-03
    C:\dev\roo-sourcecode\roo>_
  5. If you don't see the output, a key must first be created. Use gpg –gen-key, and it will walk you through a series of steps for creating a key. Then verify that your newly created key was generated using gpg –list-secret-keys.
  6. Next, you need to publish your key to a public key server. Take note of the sec key ID shown from the –list-secret-keys. In my case, it's key ID 2F96093B. Push your public key to a key server via gpg –keyserver hkp://pgp.mit.edu –send-keys 2F96093B (change the key ID at the end).
  7. Some Roo modules require JARs that are not already in OSGi form. That is, they don't have an OSGi-aware manifest. Roo has a special project called wrapping that can convert normal JARs into OSGi JARs. You'll need to run the wrapper before trying to work with Roo. Without the wrapper, you will see errors stating that Maven cannot find org.springframework.roo.wrapping.some_module. To create the wrapped JARs, from the root Roo checkout location, type:
    	cd wrapping
    	mvn clean install 
    	cd..
  8. Next, run the mvn clean install command. (Maven V2 should be installed on your system. If not, install it now.) Maven will prompt you for the password/passphrase of your key (you entered the passphrase while creating GPG key) every time you build source code. Type the passphrase and press Enter. It will take a couple of minutes to build the source code.

Process for building Spring Roo source on Windows

Building source code on Windows is a bit more difficult as compared to Ubuntu. Follow these steps:

  1. Install Git, a distributed source code-control management system. To start the process, you need to install Git on your windows machine. I installed msysGit on my Windows machine. If you already have Git installed, you can skip this step. When you install msysGit, it will ask for an installation location. It will open a command prompt and start firing a lot of commands. This will continue for a minute or so. After the install, you will see a screen as shown in Listing 4.
    Listing 4. Installing msysGit
            { test "$bindir/" = "$execdir/" || \
                   { rm -f "$execdir/git.exe" && \
                   test -z "" &amp;&amp; \
                   ln "$bindir/git.exe" "$execdir/git.exe" 2>/dev/null || \
                   cp "$bindir/git.exe" "$execdir/git.exe"; } ; } && \
            { for p in git-add.exe git-annotate.exe git-apply.exe git-archive.exe 
    git-bisect--helper.exe git-blame.exe git-branch.exe git-bundle.exe git-cat-file.exe 
    git-check-attr.exe git-check-ref
                    rm -f "$execdirf$p" && \
                    ln "Sexecdir/git.exe" "Sexecdir/$p" 2>/dev/null ll \
                    ln -s "git.exe" "$execdir/$p" 2>/dev/null || \
                    cp "Sexecdir/git.exe" "$execdir/$p" Il exit; \
             done; } && \
            { test x"git-renote-https.exe git-renote-ftp.exe \
    git-renote-ftps.exe" = x ll \
                    { for p in git-remote-https.exe git-remote-ftp.exe \
    git-remote-ftps.exe; do \
                    rm -f "$execdir{$p" && \
                    ln "Sexecdir/git-remote-http.exe" "$execdir/$p" 2>/dev/null ll \
                    ln -s “git-renote—http.exe" "$execdir/$p" 2>/dev/null || \
                    cp "Sexecdir/git-remote-http.exe" "Sexecdir/$p" ll exit; \
              done; } ; } && \
            ./check_bindir "z$bindir" "z$execdir" "Sbindir/git—add.exe"
    
    -------------------------
    Hello, dear Git developer.
    
    This is a minimal MSYS environment to work on Git.
    
    You are in the git working tree, and all is ready for you to hack.
    
    Welcome to msysGit
    
    Run 'git help git' to display the help index.
    Run 'git help <command>' to display help for specific commands.
    Run '/share/msysGit/add-shortcut.tcl' to add a shortcut to msysGit.
    
    It appears that you installed msysGit using the full installer.
    To set up the Git repositories, please run /share/msysGit/initialize.sh
  2. Set the Git environment variable. Git is required to be set up in your Windows path. Add ${MSYSGIT}\msysgit\bin and {MSYSGIT}\msysgit\mingw\bin in your Windows path where ${MSYSGIT} is the location where msysGit is installed. Open a new command prompt and enter git. You will see the output in Figure 7.
    Listing 5. Git command prompt
    C:\>git
    usage: git [--version] [--exec-path[=GIT_EXEC_PATH]] [--html-path]
               [-pl--paginate|I--no-pager] [--no-replace-objects]
               [--bare] [--git-dir=GIT_DIR] [--work-tree=GIT_WORK_TREE]
               [-c name=value
               [--help] COMMAND [ARGS]
    The most commonly used git commands are:
       add        Add file contents to the index
       bisect     Find by binary search the change that introduced a bug
       branch     List, create, or delete branches
       checkout   Checkout a branch or paths to the working tree
       clone      Clone a repository into a new directory
       commit     Record changes to the repository
       diff       Show changes between commits, commit and working tree, etc
       fetch      Download objects and refs from another repository
       grep       Print lines matching a pattern
       init       Create an empty git repository or reinitialize an existing
       log        Show commit logs
       merge      Join two or more development histories together
       mv         Move or rename a file, a directory, or a symlink
       pull       Fetch from and merge with another repository or a local bra
       push       Update remote refs along with associated objects
       rebase     Forward-port local commits to the updated upstream head
       reset      Reset current HEAD to the specified state
       rm         Remove files from the working tree and from the index
       show       Show various types of objects
       status     Show the working tree status
       tag        Create, list, delete or verify a tag object signed with GPG
    
    See ’git help COMMAND’ for more information on a specific command.
    C:\>_
  3. Checkout Spring Roo using Git. In this step, you will create a local clone of Spring Roo by checking out the latest source using Git. Open a command prompt and go to the location where you want to checkout Spring Roo. Enter git clone git://git.springsource.org/roo/roo.git . Wait until it is finished. This will create a new folder named roo at the location where you checked out Spring Roo.
  4. Download and install GPG for Windows. GnuPG is GNU's tool for secure communication and data storage. It can be used to encrypt data and to create digital signatures. Roo uses GPG to automatically sign build outputs. Once you have installed GPG, use gpg –list-secret-keys. You should see output similar to Listing 6.
    Listing 6. Result of gpg list command
    C:\dev\roo-sourcecode\roo>gpg --1ist-secret-keys
    C:/Users/xebia/AppData/Roaming/gnupg\secring.gpg
    sec 2048R/2F96093B 2010-07-03
    uid                shekhar (spring-roo) <shekhargu1ati84@gmai1.com>
    ssb 2048R/B77E5C63 2010-07-03
    C:\dev\roo-sourcecode\roo>_
  5. If you don't see the output, it means you first need to create a key. Use gpg –gen-key. It will walk you through a series of steps for creating a key. Then verify that your newly created key was generated by using gpg –list-secret-keys.
  6. Publish your key to a public key server. Take note of the sec key ID shown from the –list-secret-keys. In my case, it's ID 2F96093B. Push your public key to a key server via gpg –keyserver hkp://pgp.mit.edu –send-keys 2F96093B. (Change the key ID at the end).
  7. Build the wrapper project first. Some Roo modules require JARs that are not already in OSGi form. That is, they don't have an OSGi-aware manifest. Roo has a special project called wrapping that can convert normal JARs into OSGi JARs. You'll need to run the wrapper before trying to work with Roo. Without the wrapper, you'll see errors stating that Maven cannot find org.springframework.roo.wrapping.some_module. To create the wrapped JARs, from the root Roo checkout location, type:
    	cd wrapping
    	mvn clean install 
    	cd..
  8. Run the mvn clean install command. (Maven V2 should be installed on your system. If not, do so now.) It will prompt you for the password/passphrase of your key (you entered the passphrase while creating GPG key) every time you build source code. Type the passphrase and press Enter. It will take a couple of minutes to build the source code.
  9. Set up the environment variable ROO-DEV in your system settings, which should point to the bootstrap folder within the Roo project. You should also add this variable to the PATH environment variable, as shown in Figure 3.
Figure 3. Setting up ROO-DEV variable
Screenshot showing the Edit System Variable entry box

You can now work with the latest development version of Roo. Open the command prompt, create a new folder called mkdir roo_dev_demo, and fire the roo-dev command. You will see the screen shown in Listing 7.

Listing 7. ROO-DEV shell
C:\Users\xebia\demo\conference>roo
    ____  ____  ____
   / __ \/ __ \/ __ \
  / /_/ / / / / / / /
 / _, _/ /_/ / /_/ /
/_/ |_|\____/\____/       1.1.B.RELEASE [rev 793f2b0]
Welcome to Spring Roo. For assistance press TAB or type "hint" then hit ENTER.
roo>

You may want to update the Spring Roo source code so that you work with the latest version of Spring Roo. Open a command prompt and go to the source code location of Spring Roo. Fire the git pull command, which will pull all the remote changes into your local clone, and then do a mvn clean install to build the updated sources.


Conclusion

At this point, we have built a simple web application without even opening our editor or referring to any documentation. The application lets you do CRUD operations on the entities. I hope you see that Roo delivers serious productivity gains to the Java developers. It uses mature and stable technologies that most developers already know.

In Part 2, we make our application more secure, add internationalization support, add messaging support (SMTP and JMS), and customize the application. We will also take a look at a database reverse-engineering feature of Roo, and convert this application to a full-featured enterprise application.

Resources

Learn

Get products and technologies

Discuss

  • Participate in developerWorks blogs and get involved in the developerWorks community.
  • Get involved in the developerWorks community. Connect with other developerWorks users while exploring the developer-driven blogs, forums, groups, and wikis.

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Open source on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source, Java technology
ArticleID=618764
ArticleTitle=Introducing Spring Roo, Part 1: Building from source
publish-date=04102012