To illustrate how much Roo can help you boost your productivity on the Spring plat
form, let’s take a quick dive into Spring Roo by running one of the sample scripts, pizzashop.roo, provided by the Roo project team. This file is located in the Roo installation folder called samples, along with a number of other example scripts.
Other Roo scripts
To experiment with a more complex model, create additional empty directories and experiment with the following prebuilt scripts:
bikeshop.roo —This is a sample website for a bicycle shop that uses the JSF web framework.
clinic.roo—The Pet Clinic is a simple Spring sample application that shows off a somewhat complex set of relationships.
embedding.roo—This shows examples of embedding various media objects from Twitter, YouTube, UStream, Google Video, and others.
expenses.roo—This is an expense tracking system, using Google Web Toolkit and Google App Engine.
multimodule.roo—This shows off Roo’s support for multimodule Maven projects.
vote.roo—This is a simple voting system, using Spring MVC and Spring Security.
wedding.roo—This sets up a wedding planner system, and includes Selenium web tests, email support, and security.
You can find these scripts in the /samples folder of the Roo software installation directory. Anything placed in this directory is available for execution using the script command.
1.3.1 The pizzashop.roo sample
The pizzashop.roo sample is a simple demonstration application that simulates a basic pizza shop. It allows the user to define bases, toppings, pizzas‚ and orders.
13 Roo by example—the Pizza Shop
Let’s run the script to create the application. Create an empty directory some- where called pizzashop, and open your OS command-line shell in that directory. Fire up the Roo shell with the roo command:
$ roo script pizzashop.roo [lots of activity and output]
Script required 33.005 seconds to execute
$
RUNNING A SCRIPT FROM THE COMMAND LINE If you want to run a Roo script file, you can just use roo script scriptfile and Roo will execute the script.
You’ll see Roo go to work, executing commands and building your project. If you’re watching the directory from a file manager, you’ll see it quickly expand into a full- fledged project structure.
What just happened? Everything! Roo just built a fully configured Spring applica- tion with the following features:
A JPA container, using EclipseLink as the backing object-relational mapping (ORM) API
Four JPA entities, which are classes that map to tables in databases, namely Pizza.java, Base.java, Topping.java, and PizzaOrder.java
Four JPA repositories that persist data to the database (commonly known as data access objects—DAOs—outside of the JPA world)
A Spring MVC web application to input and display data, interacting with the four JPA entities via the repositories
Now that we’ve let Roo do its magic, let’s build the application, launch it, and kick the tires on your new application.
1.3.2 Running the Pizza Shop with Maven
Believe it or not, you’re ready to run the application. Roo configures a complete Maven-based build, even preconfiguring both the Tomcat and Jetty web servers for you to experiment with. Let’s use the Jetty web server to launch the application:
$ mvn package jetty:run
Maven replies by building the application, and then runs the Jetty web server on port 8080.
IF TOMCAT IS YOUR PREFERENCE... You can run Tomcat by using mvn package tomcat:run. Roo configures both Jetty and Tomcat web servers for your test- ing. You can also deploy a Roo application on any application server that accepts a WAR deployment. Just use the mvnpackage command to generate your WAR, which will be located in the target folder.
Open your browser to http://localhost:8080/pizzashop and view the home page as shown in figure 1.2. Executing the Maven package goal guarantees that you run against the latest changes to your application.
Figure 1.2 The Pizza Shop home page
This looks like a typical CRUD-based application, but looks can be deceiving. This application is a fully configured Spring MVC web application, complete with the latest version of Spring (3.0.6 at the time of writing), JPA 2.0 persistence, the EclipseLink JPA Provider, an in-memory Hypersonic database instance, entities, controllers, views, a service and persistence tier, and even a JSON-based web service interface.2
1.3.3 Creating toppings—forms
Let’s create a new topping by clicking on the Create New Topping menu item on the left-hand menu system. Click on the Name: field. You’ll see a prompt to enter the name because it’s a required field. Refer to figure 1.3. (We’ve omitted the full-page view on these images to focus on the important elements. All pages show a full menu, title bar‚ and footer.)
Figure 1.3 Required field checks appear visually
Try clicking on SAVE without entering a topping. Spring should have turned the input field yellow and marked it with a triangle warning, as depicted in figure 1.4.
Figure 1.4 Warnings for missed fields displayed in yellow
CRUD—create, read, update, delete—just the basics of managing application entities
2
15 Roo by example—the Pizza Shop
Roo performs client-side validation against your entities. We discuss this in detail in chapter 3. Enter a few choices, perhaps Brie, Sauce, Mushrooms, and Swiss Chard (Swiss Chard?). Each time you save a choice, you’ll see something like figure 1.5, a confirmation of the saved results as a separate page.
Figure 1.5 The save/edit confirmation page
Clicking the edit icon (the page with the pencil) will take you to a page similar to the creation form, except that it’s working with an already persisted entity.
Finally, if you click the List all Toppings menu item, you’ll see a list of the toppings you’ve already entered, as shown in figure 1.6.
Figure 1.6 The listing page, complete with pagination
As you see in figure 1.6, Roo provides paging support. It also enables viewing, editing, and removing of entities using icons on each row, as well as creating a new one using the new page icon to the left of the list results paging control at the bottom.
1.3.4 Creating a pizza form—dependencies
Let’s look at a slightly more complicated form—the pizza form. Each pizza is com
prised of a base and one or more toppings. You need to be able to create your pizza and choose your toppings and base from the ones entered before.
Click on the Create new Pizza link. You’ll see the form in figure 1.7.
Figure 1.7 Creating a new pizza
Roo automatically creates the multiselect list for Toppings, and a single-item select list for the Base. The shell has the ability to watch your entities, detect relationships, and automatically update your web forms and controllers with widgets to pick from your related entities.
Try clicking through the application. Start with bases and toppings; create your perfect pizza components. Create some pizzas based on those bases and toppings, and finally, experiment with placing an order. You’ll see the Roo client-side validations for invalid data, drop-down lists of related data, and if you take enough time to enter a lot of data, paging support. And all of this within 49 lines of Roo script code—not a single user-defined line of code.
1.3.5 JSON-based web services with the Pizza Shop
Spring Roo even configures your controllers to support JSON-based web service calls.
If you’re on a Unix/Mac machine, and have installed the Unix curl command-line tool, the script even documents several curl commands you can use to test the web ser
vice side of this application. For example, to create a Thin Crust base, you’d issue a POST call to the pizzashop/bases URL, passing it JSON data, as shown next:
curl -i -X POST -H "Content-Type: application/json" ➥
-H "Accept: application/json" -d '{name: "Thin Crust"}' ➥
http://localhost:8080/pizzashop/bases
BOOK CONVENTION: THE LINE ARROWS FOR LONG LINES Just as Roo creates long class and package names, Roo and operating system example commands are equally sprawling. Whenever you see the line arrow icon don’t hit Return; just keep typing. This is in contrast to the Unix OS line continuation character, \, which can be typed.
Note the data sent in JSON format to create a new pizza base named Thin Crust; it was JSON data. Curl will respond with the result of the web service call, which is an HTTP 201 response code:
HTTP/1.1 201 Created ...
If you open the web application and review the listing of pizza bases, you’ll now see the Thin Crust base appear.
To fetch a list of pizza bases, you’d just issue a GET call to the pizzashop/bases URL:
curl -i -H "Accept: application/json" ➥
http://localhost:8080/pizzashop/bases
Roo happily responds with the JSON data:
HTTP/1.1 200 OK ...
[{"id":1,"name":"Deep Dish","version":1}, {"id":2, "name":"Whole Wheat","version":1}, {"id":3,"name":"Thin Crust","version":1}]
There! Easy RESTful web service integration.
Roo by example—the Pizza Shop 17
1.3.6 Wrapping up the walk-through
Practice creating a few toppings, bases, pizzas‚ and orders. Remove something and see how Roo asks for a confirmation. Get used to the user interface. You get these features for free, all by asking Roo to configure Spring MVC and scaffolding your entities.
ROO AND WEB FRAMEWORKS Roo installs the web framework Spring MVC if you request it. But there are a number of web frameworks available to Roo directly, including Spring Web Flow (as part of Spring MVC), Google Web Toolkit, JavaServer Faces (in Roo 1.2), and Vaadin. These are all enabled by various Roo add-ons, some of which are installed with Roo itself.
You aren’t required to use Roo’s preconfigured frameworks. You can inte
grate with any other framework you want to, including Struts, Stripes, Flex‚ or a pure JavaScript application. But if you wish to install your web framework into a number of Roo-managed applications, you may wish to write your own Roo add-on and share it with your developers or the world.
You can terminate the application at this point. Go to your command window and shut down Jetty by hitting [CTRL]-[C].
I RESTARTED THE WEB APPLICATION. WHERE’S MY DATA? If you run the applica
tion server again, you may find that the data you entered before is missing.
This is because Roo’s default behavior is to re-create the database on startup.
We discuss how to customize this behavior in chapter 3.
Not bad for just a few lines of Roo script code. Let’s take a few minutes and review the script that created your application.
1.3.7 The Pizza Shop script
The Pizza Shop script file, samples/pizzashop.roo in the Roo installation directory, is approximately 48 lines of scripting text, including comments, but the script does a lot of configuration. Let’s walk through some of the commands in this script and touch on what they do.
CREATING THE PROJECT
First, the script creates a Roo project, defining the Java package structure that Roo will use to store objects that it generates:
roo> project --topLevelPackage com.springsource.pizzashop
At this point in time, Roo just defines the project as a JAR file—nothing yet tells it that you need a web application configuration. Roo is flexible and won’t configure more than it needs to.
DATABASE SETUP
Next, the script configures the database:
roo> jpa setup --provider ECLIPSELINK --database H2_IN_MEMORY
This command does quite a bit of work, setting up your JPA database persistence tier.
We describe the work Roo does in depth in chapter 3.
CREATING JPA ENTITIES
The script then sets up the four JPA entity classes—Base, Topping, Pizza, and Pizza- Order. The entity jpa and field commands comprise the content of most of this script. Here’s an excerpt that installs three entities—Base, Topping, and Pizza—and begins to add fields to each of them. Notice the options, such as --sizeMin and --notNull. We talk about those in chapter 3, as well as the field reference and field set commands, which establish relationships between entities:
roo> entity jpa --class ~.domain.Base --activeRecord false ➥
--testAutomatically
roo> field string --fieldName name --sizeMin 2 --notNull
roo> entity jpa --class ~.domain.Topping --activeRecord false ➥
--testAutomatically
roo> field string --fieldName name --sizeMin 2 --notNull roo> entity jpa --class ~.domain.Pizza --activeRecord false ➥
--testAutomatically
roo> field string --fieldName name --notNull --sizeMin 2 roo> field number --fieldName price --type java.math.BigDecimal roo> field set --fieldName toppings --type ~.domain.Topping roo> field reference --fieldName base --type ~.domain.Base SETTING UP REPOSITORIES
The next script section creates Spring JPA repositories using the Spring Data JPA API. These are the objects that talk to the database in the service-based Spring architecture we discussed earlier:
repository jpa --interface ~.repository.ToppingRepository ➥
--entity ~.domain.Topping
repository jpa --interface ~.repository.BaseRepository ➥
--entity ~.domain.Base CONFIGURING SERVICES
Roo can also expose transactional services using Spring Beans. These services are con
figured to manipulate the entity passed to them, and will delegate calls to the reposi
tory methods to find, create, update‚ and delete data:
service --interface ~.service.ToppingService --entity ~.domain.Topping service --interface ~.service.BaseService --entity ~.domain.Base CONFIGURING JSON
The rest of the script concerns the web interface. Roo can optionally expose JSON to the web tier if needed. These commands provide JSON support for the web services we reviewed earlier:
json all --deepSerialize web mvc json setup web mvc json all
19 Roo application architecture models
SPRING MVC
And finally, the script generates the web application. This code literally installs Spring MVC, configures the website layout, builds controllers for each entity automatically, and places the controllers in the web subpackage of the root package:
web mvc setup
web mvc all --package ~.web
THE TILDE (~) AND topLevelPackage Take special notice of the --topLevel- Package attribute of the project command. This setting allows you to use the previously mentioned ~. (tilde-period) shortcut in future commands as a base package to build your other components from. Roo also configures the proj
ect to detect new Spring components from this package downward.
With only a few lines of Roo commands, you've already generated a complete Spring MVC web application. This script configures a number of technologies, including
The Spring Framework
The EclipseLink ORM implementation
The Java Persistence API, version 2.0
Java EE Bean Validations (JSR-303)
Spring MVC
JSON data translation with the Flexjson library
Apache Tiles
Logging via the slf4j framework and log4j
ROO—NOT JUST FOR WEB APPS Although the Pizza Shop is a web-based, data- driven application, you may be building a message-driven system, perhaps using JMS or the Spring Integration API. Spring Roo will help you configure and manage the bulk of your project, regardless of whether it’s a web applica
tion or a standalone program, saving valuable time you would otherwise spend wiring together your infrastructure.
Now that you’ve created your application, kicked the tires, and explored the script, let’s dig deeper into the project’s application architecture.