As you know from "Java development 2.0: You can borrow EC2 too," Amazon's Elastic Compute Cloud (EC2) is a generic infrastructure service that hosts virtual machines (of the Linux®, OpenSolaris, or even Windows® persuasion) on which you can run anything you'd like. You can run any Java application — including a Web application that uses Hibernate and Spring, as I'll show you in this article — provided you create or borrow a virtual machine, also known as an Amazon Machine Image (AMI) or instance.
The community behind and around Amazon's Web services offerings has been quite busy over the last few years, and you can choose from an entire catalog of public virtual machines to use at your pleasure (see Resources). Linux comes in many flavors, so as you can imagine the catalog is packed with various configurations of software and related tools. For this article, all I'm looking for is an AMI that:
- Already has a Java version installed (preferably a recent version)
- Has a servlet container, such as Tomcat
- Has a freely available database, such as MySQL
I also have the option of using a blank-slate virtual machine (so to speak), where I can then install these components. But it's nice to know that you can find pretty much any configuration if you take the time to look for it. In fact, for the most part, the hardest aspect of EC2 provisioning is finding a particular virtual machine that suits your tastes. Once you've found one, the fun starts! I did find one that meets my requirements, and I'll show you how to use it. It's quite simple, especially if you've already installed the Eclipse AWS plug-in that I went over in the previous article.
The Eclipse AWS plug-in allows you to search for, launch, and terminate instances; plus, provided you've properly configured a key pair (which the plug-in handles quite well), you can ssh via a terminal window to a particular image to do further configuration.
Like last time, however, when I started showing you the ins and outs of EC2, it makes sense to build a quick Java application before I get too involved in launching public AMIs. By using the Grails framework, the application will leverage Spring and Hibernate (and thus an underlying persistent store).
Along with the use of borrowed infrastructures, a fundamental aspect of Java development 2.0 is the leveraging of open source to build applications from top to bottom. By using open source tools, frameworks, and even solutions, companies can assemble software applications quickly because they themselves don't need to write as much code. When it comes to open source solutions that make development quick and arguably a lot easier, two frameworks that come to mind are Spring and Hibernate.
Practically all Java shops the world over use the Spring framework to build applications. Although it is known primarily as an inversion-of-control (IoC) framework, it really has become the backbone of Java development. (Spring is an aspect-oriented programming [AOP] framework, an OSGi container, a Web framework, and more.) Not to be outdone, Hibernate is the 500-pound gorilla in the Java object-relational mapping (ORM) space. The adoption rate of Java Data Objects (JDO) (which I demonstrated with Google App Engine in this series' first installment) isn't anywhere close to Hibernate's. Thus, when I think of Java development today and in the future, both Spring and Hibernate are most likely in the mix. (That's not to say that you need both frameworks to get a particular job done. It's just that for most of the time, these two frameworks will meet practically all of your needs.)
Groovy, meanwhile, is a development platform that in essence makes Java development a heck of a lot easier (see Resources). Groovy is really just the Java language without a lot of the syntax. It allows you to focus on building solutions quickly rather than spending many cycles writing a lot of straight Java code to solve the same problem. (Groovy isn't alone in this respect. A host of other languages that run on the JVM can tackle the same exact issue.) For me, Groovy is just another JAR file in my mix of tools.
So, when I think of building an application quickly, I think of Groovy, Spring, and Hibernate. And in the case of Web applications, one particular framework puts all three of them together quite nicely: Grails. Grails is built on Spring and based on Groovy. And Grails Object Relational Mapping (GORM) — the Grails ORM implementation — uses Hibernate under the hood.
This is not primarily an article about Grails. (I recommend you read Scott Davis's Mastering Grails series if you want to — well — master Grails.) That being said, building a simple Web application with Grails is amazingly easy. Watch.
Getting started with Grails is simple. Follow along, and in no time you'll have a basic Web application that leverages a database (via Spring and Hibernate). First, download Grails (see Resources), unarchive it, and configure your environment by setting a GRAILS_HOME environment variable that points to your installation directory. Then add GRAILS_HOME/bin to your path. Also, be sure you've got a JAVA_HOME environment variable.
Now open up a console window or shell (depending on your operating system) and at the command prompt type:
grails create-app mytri |
This will, not surprisingly, create a Grails Web application named mytri, which is in keeping with the general theme of the triathlon-tracking application I showed you how to build with Google App Engine earlier in this series.
Next, change directories into the newly created Web application (cd mytri/) and type:
grails create-domain-class Triathlon |
You should see Grails output a few lines ending in something like:
Created DomainClass for Triathlon Created Tests for Triathlon |
Now, change directories into grails-app/domain. In this directory, you'll see a file aptly named Triathlon.groovy. Open this file in whatever editor you'd like. As in earlier articles in the series, I'm not going to spend too much time focusing on this domain. That is, for now, I'll keep things really simple (you can always embellish later); I'm going to ignore relationships and focus on a few properties of a triathlon:
- A date
- A type (sprint, half iron man, and so on)
- A name
- A location
So, add the code in Listing 1 to your Triathlon.groovy file:
Listing 1. Simple domain object representing a triathlon
class Triathlon {
static constraints = {
classification(inList:["Sprint", "Olympic", "1/2 Iron Man", "Iron Man"] )
}
String name
String location
Date eventDate
String classification
}
|
Note how the object's constraints section specifies that classification can only be one of four types. Save and close the file.
Next, go back to the project's home directory (mytri) and type:
grails generate-all Triathlon |
This command creates the proverbial view and controller part of Model-View-Controller (MVC). The Triathlon object is the model.
Now take a deep breath, because you're done. You just created a simple Web application that creates, updates, removes, and reads triathlons in a database. Exciting, isn't it? To run the application, type:
grails run-app |
Open up a browser and go to http://localhost:8080/mytri. You'll see some generic interfaces generated by Grails that support CRUD (create, read, update, delete) on my domain object.
For instance, when the mytri application loads (see Figure 1), you should see a link corresponding to the TriathlonController object that Grails created when you ran the generate-all command:
Figure 1. Default Grails application home page
Clicking the TriathlonController link shows that the underlying data store is empty. But if you then click the New Triathlon link, you'll be presented with a nice form for creating triathlons, as shown in Figure 2:
Figure 2. Form for creating a triathlon
Fill out the form with some data and click the Create link, and you'll be directed back to the list of available triathlons. And wouldn't you know it? Your newly created object is there, as shown in Figure 3:
Figure 3. Successful triathlon creation
Behind the scenes, Grails uses an in-memory database known as HSQL; however, you'll next export the schema Grails is using and have that ready in order to create a database table inside of MySQL.
Configuring Grails to interact with a database other than HSQL is quite simple. Go into the mytri/grails-app/conf directory and open the DataSource.groovy file with your favorite editor. In the file's dataSource section, add the following line:
dialect=org.hibernate.dialect.MySQLDialect.class |
This line tells Grails to use Hibernate's MySQL dialect; in particular, you'd like Grails to produce a valid MySQL Data Definition Language (DDL) file. Consequently, next, in your console, make sure you are in the project's home directory and type:
grails schema-export |
This process yields a file dubbed sql.ddl, which consists of the statements you need to run to create a proper table inside of MySQL (a step you'll perform later). Finally, remove the dialect line from the DataSource.groovy file — you'll put it back later in a different spot.
Provisioning an Amazon instance
Wow. You've done a lot already and haven't even touched EC2 yet. That's a good thing, though. The beauty of EC2 and similar services is that they are simple and can be fired up at a moment's notice. Accordingly, open Eclipse (install the AWS plug-in and configure it if you haven't yet — see last month's article for instructions, if needed) and open the Amazon EC2 Management perspective. From there, click on the EC2 AMIs view. You should see a rather cryptic list containing IDs and manifests, and a text box on the upper far right of the view, as shown in Figure 4:
Figure 4. AMI listings
In the rather unobvious text box, type ami-aa5abac3. This is the ID of the handy AMI provided by Java Web Apps in a Box. Figure 5 shows the result:
Figure 5. The AMI I want
As you can see in Figure 5, the ami-aa5abac3 AMI has been located, and its manifest contains the words tomcat and mysql — not bad, we're getting somewhere. Next, select the AMI, right-click, and select the launch option. You'll be presented with a new dialog that allows you to configure the launching of the AMI. When launching an AMI, you should select a key pair and a security group (just as you did in "Java development 2.0: You can borrow EC2 too"), as shown in Figure 6:
Figure 6. Configuring AMI launch options
Click the Finish button, which — as you can probably guess — launches the AMI somewhere out in the ether of the Internet. You can see in the Eclipse AWS EC2 Instances view, shown in Figure 7, that your instance's launch is in a pending state:
Figure 7. Eclipse AWS EC2 Instances view
The state of the AMI will change from launching to running. This might take a bit of time, so be patient. Once the instance is running, you'll notice that the Eclipse AWS EC2 Instances view shows the public DNS for your AMI. This will be handy for navigating to your Web application later.
You'll need a terminal session to further configure MySQL. Select the instance, right-click, and select the Open Shell option. Depending on your local machine's operating system, you might need to find a shell that supports SSH. (If you're on Windows, you can use Putty; see Resources).
While still in the shell you opened from within Eclipse that is pointing to your newly started AMI, log into MySQL via the command:
mysql -u root --password=root |
Then create a new user for your Grails instance:
mysql> CREATE USER 'grails'@'localhost' IDENTIFIED BY 'groovy'; |
And then give this user privileges for the database:
mysql> GRANT ALL ON *.* to 'grails'@'localhost'; |
Next, create a database (or schema, depending on how you look at things in the database world):
mysql> create database mytri; |
You must then start using that newly created database in order to create tables:
mysql> use mytri; |
Finally, execute the last line (without any breaks) from the sql.ddl file:
mysql> create table triathlon ( id bigint not null auto_increment, version bigint not null, classification varchar(12) not null, event_date datetime not null, location varchar(255) not null, name varchar(255) not null, primary key (id)); |
Now your MySQL database is ready for use. All that's left is to finish configuring Grails to use it.
Configuring Grails to use MySQL
Download the MySQL JDBC driver (see Resources) and place it in the mytri/lib directory. Next, open the DataSource.groovy file and update the production section, as shown in Listing 2:
Listing 2. Adding MySQL driver and dialect configuration to DataSource.groovy
production {
dataSource {
driverClassName = "com.mysql.jdbc.Driver"
username = "grails"
password = "groovy"
dialect=org.hibernate.dialect.MySQLDialect.class
url = "jdbc:mysql://localhost/mytri"
}
}
|
This change simply points a production instance of Grails at an underlying MySQL database running on the same machine (localhost). Of course, the localhost instance is an AMI running somewhere out there in the ether.
Deploying a Grails application via Tomcat's management interface
A Grails application — like any other Java Web application — gets deployed as a WAR file. Accordingly, back in your computer's shell (that is, the shell you've been using to work with Grails, not the shell that's pointing to the EC2 instance), type:
grails -Dgrails.env=prod war mytri.war |
This will create a file aptly named mytri.war. From here, it's a matter of using Tomcat's management interface to load this application on your newly fired-up AMI. You could, by the way, scp mytri.war onto the target AMI. The choice is yours; in this case, I prefer using Tomcat's interface because Tomcat is already running and I don't have to find its path on the underlying file system.
Configuring Tomcat's management interface
Before you can use Tomcat's management interface, you must enable it properly on the EC2 image, because the AMI has been configured by default (for security reasons) to disallow the interface:
- Go back to the shell session pointing to the AMI instance and find the tomcat-users.xml file located in the /usr/local/tomcat-6.0.20/conf directory.
- Open this file and add a new role called
manager. - Create a new user (or use an existing one) and ensure that this user has the
managerrole. - Restart Tomcat. You can either reboot your instance via the Eclipse console or simply go into the /usr/local/tomcat-6.0.20/bin directory and run the stop script followed by the start script — the choice is up to you.
Go back into the Eclipse EC2 Instances view, right-click on the instance, and select Copy Public DNS Name. Then paste that name into your browser's location box. You should see a lovely Tomcat welcome screen — if not, wait a few minutes and try again, because it might take a while for the network to catch up with you.
Once the page loads, click the Tomcat Manager link on the left-hand menu. You'll be prompted for a username and password. Enter the username and password you configured earlier. Once the management interface loads, scroll down to the War file to deploy form, click the Browse button, and find mytri.war. Finally, click the Deploy button. This is a big WAR file, so don't worry if it takes a bit of time.
Once the upload finishes, you should see the mytri application listed in the Applications section. Click the mytri application link. You should be treated to a bit of deja vu, because it looks just like the screen in Figure 2. From here, you should be able to create new triathlons — only this time, they reside in MySQL on an EC2 instance somewhere on the Internet. Was that easy or what?
Don't forget to shut down the AMI once you're satisfied things are working well. Remember, Amazon is charging you by the hour (albeit not much). You can terminate your AMI by right-clicking on the instance in the EC2 Instances view in Eclipse. Terminating an AMI wipes everything out — that is, you'll have to set up the MySQL database again, for example, should you want to play with triathlons again. (Another Amazon service, Elastic Block Storage, facilitates keeping this kind of data long-term by allowing transient data to survive AMI instances.)
As you can see once again, both aspects of Java development 2.0 are present in EC2: you can fully leverage open source packages like MySQL, Tomcat, and Grails (which uses Spring and Hibernate behind the scenes) on a borrowed infrastructure that costs far less than acquiring the hardware resources yourself. What's more, EC2 is quite efficient to set up and can scale far beyond what you can do for the same cost with your own hardware. In fact, if it felt like you didn't do all that much in this article, that's the point!
Next month, I'll give you a look at CouchDB, a document-oriented database that's is distinctly different from, say, MySQL. You'll find out why some people are calling it the database of the future.
Learn
-
Amazon Elastic Compute Cloud (Amazon EC2): Visit home base for Amazon's EC2.
-
"Java development 2.0: You can borrow EC2 too" (Andrew Glover, developerWorks, September 2009): Get a hands-on introduction to EC2.
- Java Web Apps in a Box: Java Web Apps in a Box is a cloud-based solution that provides Java 6, Tomcat, and MySQL.
-
Mastering Grails (Scott Davis, developerWorks): This series explores Grails, a modern Web development framework that mixes familiar Java technologies like Spring and Hibernate with contemporary practices like convention over configuration.
-
"Storage made easy with S3" (Andrew Glover, developerWorks, April 2009): Learn how to use the open source JetS3t library to leverage Amazon's S3 cloud service for storing and retrieving data.
-
"Leveraging Amazon Web Services for enterprise application integration" (Brian J. Stewart, developerWorks, June 2009): Discover how to leverage XML and Amazon Web Services to integrate enterprise applications, and to build cross-platform application-integration capabilities using the Microsoft .NET and Java platforms.
-
"Cloud computing with Amazon Web Services, Part 3: Servers on demand with EC2" (Prabhakar Chaganti, developerWorks, October 2008): This article introduces you to the virtual servers provided by Amazon EC2. Learn how EC2 can help you configure your applications' computing requirements on the fly and adjust capacity based on demand.
-
"Cloud computing versus grid computing" (Judith Myerson, developerWorks, March 2009): Learn how you can use Infrastructure as a Service to get a full computer infrastructure using Amazon's EC2 and see the similarities, differences, and issues to consider in grid and cloud computing.
-
Cloud Computing: Visit
IBM® Cloud Computing Central for a wealth of cloud resources.
-
Browse the
technology bookstore for books on these and other technical topics.
-
developerWorks Java technology zone: Find hundreds of articles about every aspect of Java programming.
Get products and technologies
- AWS Toolkit for Eclipse: Install the Eclipse plug-in for EC2.
- Amazon Machine Images (AMIs): Browse the public AMI collection.
- Grails: Download Grails.
- JDBC Driver for MySQL: Download the MySQL JDBC driver.
- PuTTY: Download PuTTY, a freely available terminal for Windows that supports SSH.
-
developerWorks Cloud Computing Resource Center: Access IBM software products in the Amazon Elastic Compute Cloud (EC2) virtual environment.
Discuss
-
Amazon Web Services Discussion Forums: Participate in the EC2 discussion forum.
- Get involved in the My developerWorks community.

Andrew Glover is a developer, author, speaker, and entrepreneur with a passion for behavior-driven development, Continuous Integration, and Agile software development. You can keep up with him at his blog.




