SlideShare a Scribd company logo
Building Auto-scalable Cloud Based
Applications using Grails 2.x and AWS Simple cloud based photo gallery application
12 • groovymag • volume four | issue seven | may, 2012
Building Auto-scalable Cloud Based
Applications using Grails 2.x and AWS
Simple cloud based photo gallery application
By Igor Stelmashenko
igor@intermobile.ca
https://plus.google.com/107671704413122133444/about
Grails and AWS combination makes creation of auto-
scalable web apps simple and fun. Learn how to create
and deploy a simple photo gallery web application using
SimpleDB, S3, SES and BeansTalk.
The recent release of Grails 2.0 introduced a great number
of very important features: a big performance boost, better
error reporting, a database migration plugin and a great look
and feel for mobile browsers are among my favorite ones.
Grails was always one of the best frameworks for rapid web
application development. Cloud services such as Amazon’s
AWS complement it with auto-scalability. You can literally
go from one to tens or hundreds of servers in a matter
of minutes by using BeanStalk. You simply upload your
application, and Elastic Beanstalk automatically handles the
deployment details of capacity provisioning, load balancing,
auto-scaling, and application health monitoring. You can add
and remove capacity with a few clicks and it won’t cost you
arm and a leg. This article will attempt to demonstrate it with
a simple example.
Let’s create a very simple photo sharing application and
call it GGallery (sources available @ https://github.com/
thezaphod/ggallery). Let’s say you have a huge collection of
photographs that you would like to share with your friends,
family, and clients. Some of these photos might get posted
on reddit.com or digg.com and you would like to make
sure your application can handle your popularity as a
photographer. You can try a running GGallery demo app @
http://ggallery.elasticbeanstalk.com/.
Let’s re-create this application step by step. We will use
Amazon Simple Storage Service (Amazon S3) for storing
our images. S3 provides a simple web services interface
that can be used to store and retrieve any amount of data.
It gives any developer access to the same highly scalable,
reliable, secure, fast, inexpensive infrastructure that Amazon
uses to run its own global network of web sites. Let’s start
with creating and AWS account at http://aws.amazon.com.
Once the account is created, go to the AWS management
console and create a ggallery bucket and upload a few of
your images at https://console.aws.amazon.com/s3/home.
Let’s create our grails application. Make sure you have
Grails 2.X installed:
$ grails create-app ggallery
$ cd ggallery
$ grails install-plugin aws
$ grails install-plugin simpledb
The AWS plug-in includes all the libraries required to take
advantage of all AWS infrastructure. SimpleDB includes
a JPA implementation for Amazon’s SimpleDB. Amazon
SimpleDB is a highly available and flexible non-relational
data store that offloads the work of database administration.
We don’t need to learn SimpleDBAPIs since we are using
a JPAimplementation.All object mapping will be done for us
automatically. We only need to configure our application to give it
permissions to access yourAWS account’s data. Find yourAWS
security credentials from a menu at the top of a right corner of the
AWS Management Console, as shown in Figure 2 (Next page).
To configure theAWS plugins, open grails-app/conf/Config.
groovy and append the configuration information below with your
ownAccess Key ID and SecretAccess Key, as shown in Listing 1.
access = ‘your access key here’
secret = ‘your secret key here’
grails {
plugin {
aws { // for S3, SES
credentials {
accessKey = access
secretKey = secret
}
s3 {
bucket = “ggallery”
}
}
}
simpledb {
accessKey = access
secretKey = secret
domainNamePrefix = grails.util.GrailsUtil.
environment
dbCreate = ‘drop-create’
}
}
Listing 1: Grails AWS plugin configuration in Config.groovy
1copylicensedtothezaphod@gmail.comviacouponcodefi9yk8j05/08/201211:57:24AM
Building Auto-scalable Cloud Based
Applications using Grails 2.x and AWS Simple cloud based photo gallery application
13 • groovymag • volume four | issue seven | may, 2012
Figure 1: The GGallery application
Figure 2: Access keys in the AWS Management Console
1copylicensedtothezaphod@gmail.comviacouponcodefi9yk8j05/08/201211:57:24AM
Building Auto-scalable Cloud Based
Applications using Grails 2.x and AWS Simple cloud based photo gallery application
14 • groovymag • volume four | issue seven | may, 2012
Let’s create Domain Objects and instruct GORM to store
objects in SimpleDB:
$ grails create-domain-class Email
$ grails create-domain-class Photo
$ grails create-domain-class Album
Listing 5: The PhotoController implementation
In PhotoController we use an injected by Grails and
instantiated by plugin service aws to authorize access to S3
files, and then enumerate all images we previously uploaded
and generate temporary public URL for the application. By
default all files are stored securely on the S3 service. The
view for the controller above simply loops through all images
and displays them as thumbnails.
package ggallery
class Photo {
String id
String filePath
String caption
String url
static mapWith = “simpledb”
}
package ggallery
import org.jets3t.service.security.AWSCredentials
import org.jets3t.service.impl.rest.httpclient.
RestS3Service
class PhotoController {
// injected
def aws
// display image directory
def index() {
def c = new AWSCredentials(
grailsApplication.config.grails.
plugin.aws.credentials.accessKey,
grailsApplication.config.grails.
plugin.aws.credentials.secretKey)
RestS3Service s3Service = new
RestS3Service(c)
def objs = s3Service.
listObjects(“ggallery”, “”, “”)
def album = new Album(title: params.
id, url: request.getRequestURL(), photos: new
HashSet())
objs.each() {
def filePath = it.key
def pUrl = aws.s3().on(“ggallery”).
publicUrlFor(1.hour, filePath)
def o = new Photo(filePath: filePath,
caption: filePath, url: pUrl)
}
[album: album]
}
}
package ggallery
class Album {
String id
String title
String url
Email email
static hasMany = [photos: Photo]
static mapWith = “simpledb”
}
package ggallery
class Email {
String id
String to
String from
String subject
String text
Album album
static mapWith = “simpledb”
}
Listing 2: Photo class definition
Listing 3: Album class definition
Listing 4: Email class definition
Let’s create a controller and view to display our images:
$ grails create-controller Photo
1copylicensedtothezaphod@gmail.comviacouponcodefi9yk8j05/08/201211:57:24AM
Building Auto-scalable Cloud Based
Applications using Grails 2.x and AWS Simple cloud based photo gallery application
15 • groovymag • volume four | issue seven | may, 2012
Listing 6: Part of the view implementation
Our application is ready to run. At this point we are able
to view all our uploaded images from S3. Let’s add album
creation capabilities and sending e-mail using Amazon
Simple Email Service (Amazon SES). SES is a highly
scalable bulk and transactional email-sending service for
businesses and developers. Amazon SES eliminates the
complexity and expense of building an in-house email
solution or licensing, installing, and operating a third-party
email service. Let’s create an Email service and Album
controller to view album and send out the E-mail.
$ grails create-service Email
Listing 8: The AlbumController
Before we can send email via Amazon SES, we need to
verify that we own the address from which we’ll be sending
email. I will verify my test account I created for this tutorial.
You will need to verify you own address. Once you are
ready to use Amazon SES to send email on production, you
request production access. This will allow you to move from
the sandbox environment to the production environment and
begin sending email to any arbitrary e-mail account.
$ grails aws-ses-verify-email
> Enter the e-mail address to verify: ggallery@
intermobile.ca
...
<g:each in=”${album.photos.sort{ it.filePath
}}” var=”obj”>
<div class=”album”>
<div class=”thumb”>
<a href=”${obj.url}”> <img
SRC=”${obj.url}” width=”208” height=”158”
BORDER=”0”></a>
</div>
<div style=”‚Ķ”>
${obj.caption}
</div>
<div style=”‚Ķ”>
<input type=”checkbox”
name=”add” value=”share” alt=”${obj.filePath}”
onchange=”share(this.checked, this.alt)” /> share
</div>
</div>
</g:each>
...
package ggallery
class AlbumController {
// injected
def aws
def emailService
def index() { }
def create() {
def msg = new Email(from: params.from,
to: params.to, subject: params.subject, text:
params.email, url: “${getSiteUrl(request)}/album/
show?id=”)
msg.save()
def album = new Album(title: params.
title, photos: new HashSet(), email: msg, url:
“${getSiteUrl(request)}/album/show?id=”)
// create album
session.images.each() { filePath ->
def pubUrl = aws.s3().on(“ggallery”).
publicUrlFor(1.hour, filePath)
def f = new Photo(filePath: filePath,
caption: filePath, url: pubUrl)
f.save()
album.photos.add(f)
}
album.save()
String albumUrl =
“${getSiteUrl(request)}/album/show?id=” + album.
id
msg.url = albumUrl
msg.save()
album.url = albumUrl
album.save()
msg.url = albumUrl
msg.save()
session.album = album
redirect(action: “show”)
// send e-mail
emailService.send(msg)
}package ggallery
class EmailService {
static transactional = false
def send(email) {
def mailId = sesMail {
from “${email.from}”
to “${email.to}”
subject “${email.subject}”
body “${email.text} n ${email.url}”
}
return mailId
}
}
Listing 7: The EmailService
$ grails create-controller Album
1copylicensedtothezaphod@gmail.comviacouponcodefi9yk8j05/08/201211:57:24AM
Building Auto-scalable Cloud Based
Applications using Grails 2.x and AWS Simple cloud based photo gallery application
16 • groovymag • volume four | issue seven | may, 2012
[AWS SES] Please check the email address ggallery@
intermobile.ca to verify it
grails> aws-ses-list-verified-emails
[AWS SES] 1) ggallery@intermobile.ca
The Album view gsp is not much different from the one we
already defined to view all our images on S3. You will find
the full source on github: https://github.com/thezaphod/ggallery/
blob/master/grails-app/views/album/show.gsp.
Our application is ready and we can now deploy it on
BeansTalk.
To deploy your applications using AWS Elastic Beanstalk,
you simply follow these steps:
1. Run $ grails war to create a standard deployable
WAR file (Java Web Application Archive).
2. Upload your WAR file to Elastic Beanstalk using the
AWS Management Console, the AWS Toolkit for
Eclipse, the web service APIs, or the command line
interface.
3. Deploy your application. Behind the scenes, Elastic
Beanstalk handles the provisioning of a load balancer
and the deployment of your WAR file to one or more
Amazon EC2 instances running the Apache Tomcat
application server.
Within a few minutes you will be able to access your
application at a customized URL (e.g. http://myapp.
elasticbeanstalk.com/).
Under the hood, Beanstalk is built using EC2 (Amazon
Elastic Compute Cloud) instances as building blocks
for scalable virtual infrastructure. All the complexity of
managing a multitude of servers is hidden behind a simple
web interface. Any of the actions performed with the web
interface can be also scripted from the command line. You
can test your running application on AWS at http://ggallery.
elasticbeanstalk.com, and the full source for this application is
on Github at https://github.com/thezaphod/ggallery.
Let’s review what we did and why Cloud services such as
Amazon AWS are a big deal. It allows you to create well
architected, scalable software services utilizing best-of-the-
breed technology and infrastructure. We’ve used Beanstalk,
SimpleDB, SES and S3. Since these services are carefully
designed and tested to scale, the architectural viability is
guaranteed. This could be one of your critical advantages
over solutions using old approaches. For example, S3
scales to a large enterprise needs for storage, Beanstalk
for application hosting and SimpleDB for databases. There
will be no big costly surprises once you attempt to scale
it up. It also illuminates needs and the overhead system
administration. It’s a self-serve, “get it when you needed
it” in a matter of minutes deal. AWS is often called an
infrastructure-as-a-service (IaaS) service. You basically have
the same building blocks any IT of any mid-sized to large
organization has without a big upfront investment and at
the fraction of the costs of owning it. If you work for a small
startup, this is a huge value proposition. Also, AWS doesn’t
have a huge learning curve. In our example, we were able
to take full advantage of SimpleDB using the same familiar
to us technology – GORM. Tools like RazorSQL will allow
you to navigate your stored data in SimpleDB as if it was a
relational database.
Have fun creating cool apps! 1copylicensedtothezaphod@gmail.comviacouponcodefi9yk8j05/08/201211:57:24AM

More Related Content

PDF
Aws setup
Randika Senanayaka
 
PPTX
Creating a Custom PowerApp Connector using Azure Functions
Murray Fife
 
PPTX
Unity and Azure Mobile Services using Prime31 plugin
David Douglas
 
PDF
Salesforce Lightning Tips & Tricks
Thinqloud
 
PDF
Google Cloud for Developers - Devfest Manila
Patrick Chanezon
 
PDF
Wave Workshop
Jason Dinh
 
PDF
Building what's next with google cloud's powerful infrastructure
MediaAgility
 
PPTX
Grails Advanced
Saurabh Dixit
 
Creating a Custom PowerApp Connector using Azure Functions
Murray Fife
 
Unity and Azure Mobile Services using Prime31 plugin
David Douglas
 
Salesforce Lightning Tips & Tricks
Thinqloud
 
Google Cloud for Developers - Devfest Manila
Patrick Chanezon
 
Wave Workshop
Jason Dinh
 
Building what's next with google cloud's powerful infrastructure
MediaAgility
 
Grails Advanced
Saurabh Dixit
 

What's hot (19)

PDF
StackMob & Appcelerator Module Part One
Aaron Saunders
 
PDF
Google Cloud - Scale With A Smile (Dec 2014)
Ido Green
 
PDF
Online mobile game server use Firebase realtime aatabase
Nguyễn Bá Thành
 
PDF
 +  = ❤️ (Firebase for Apple Developers) at Swift Leeds
Peter Friese
 
DOCX
Microsoft identity platform and device authorization flow to use azure servic...
Sunil kumar Mohanty
 
PPTX
AngularJS Fundamentals + WebAPI
Eric Wise
 
PDF
How to build Android Chat App with Firebase for 2 hours?
Nguyễn Bá Thành
 
PPTX
Introduction to Google Cloud
DSC IEM
 
PDF
Practical SQL Azure: Moving into the cloud
Timothy Corey
 
PDF
Full Angular 7 Firebase Authentication System
Digamber Singh
 
PPTX
Strategies to automate deployment and provisioning of Microsoft Azure.
HARMAN Services
 
PDF
Hands-on with AWS IoT (November 2016)
Julien SIMON
 
PDF
Paul Lammertsma: Account manager & sync
mdevtalk
 
PDF
Getting Started on Amazon EKS
Matthew Barlocker
 
PPTX
Google cloud Platform
Janu Jahnavi
 
PDF
Case study of Google Cloud Platform
David Chen
 
PDF
Cloud Security @ Netflix
Jason Chan
 
PDF
New Component Patterns in Ember.js
Matthew Beale
 
PPT
Colombo Mobile Developer MeetUp - Building Scalable Cloud Connected Mobile Ap...
99X Technology
 
StackMob & Appcelerator Module Part One
Aaron Saunders
 
Google Cloud - Scale With A Smile (Dec 2014)
Ido Green
 
Online mobile game server use Firebase realtime aatabase
Nguyễn Bá Thành
 
 +  = ❤️ (Firebase for Apple Developers) at Swift Leeds
Peter Friese
 
Microsoft identity platform and device authorization flow to use azure servic...
Sunil kumar Mohanty
 
AngularJS Fundamentals + WebAPI
Eric Wise
 
How to build Android Chat App with Firebase for 2 hours?
Nguyễn Bá Thành
 
Introduction to Google Cloud
DSC IEM
 
Practical SQL Azure: Moving into the cloud
Timothy Corey
 
Full Angular 7 Firebase Authentication System
Digamber Singh
 
Strategies to automate deployment and provisioning of Microsoft Azure.
HARMAN Services
 
Hands-on with AWS IoT (November 2016)
Julien SIMON
 
Paul Lammertsma: Account manager & sync
mdevtalk
 
Getting Started on Amazon EKS
Matthew Barlocker
 
Google cloud Platform
Janu Jahnavi
 
Case study of Google Cloud Platform
David Chen
 
Cloud Security @ Netflix
Jason Chan
 
New Component Patterns in Ember.js
Matthew Beale
 
Colombo Mobile Developer MeetUp - Building Scalable Cloud Connected Mobile Ap...
99X Technology
 
Ad

Similar to Groovymag_May-2012 (20)

PDF
Deploying, Scaling, and Running Grails on AWS and VPC
GR8Conf
 
ZIP
Rails in the Cloud
iwarshak
 
PPTX
Codestrong 2012 breakout session using appcelerator cloud services in your ...
Axway Appcelerator
 
PDF
GR8Conf 2011: Grails, how to plug in
GR8Conf
 
PPTX
App Deployment on Cloud
Ajey Pratap Singh
 
PPT
Deploying and running Grails in the cloud
Philip Stehlik
 
PPTX
Groovy & Grails - From Scratch to Production
Tal Maayani
 
ZIP
Rails in the Cloud
iwarshak
 
PPT
Fast web development using groovy on grails
Anshuman Biswal
 
PPT
JavaOne 2008 - TS-5764 - Grails in Depth
Guillaume Laforge
 
PPTX
Introduction to Grails 2013
Gavin Hogan
 
ODP
Cloud computing - an insight into "how does it really work ?"
Tikal Knowledge
 
PDF
Mastering Grails 3 Plugins - G3 Summit 2016
Alvaro Sanchez-Mariscal
 
PDF
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
nairakash2004
 
DOCX
Guide - Migrating from Heroku to AWS using CloudFormation
Rob Linton
 
PDF
Build an app on aws for your first 10 million users (2)
AWS Vietnam Community
 
PDF
Aws Technical Day 2015 - Amazon API Gateway
aws-marketing-il
 
PPTX
Spring Northwest Usergroup Grails Presentation
ajevans
 
PPT
Hosting a Rails App
Josh Schramm
 
Deploying, Scaling, and Running Grails on AWS and VPC
GR8Conf
 
Rails in the Cloud
iwarshak
 
Codestrong 2012 breakout session using appcelerator cloud services in your ...
Axway Appcelerator
 
GR8Conf 2011: Grails, how to plug in
GR8Conf
 
App Deployment on Cloud
Ajey Pratap Singh
 
Deploying and running Grails in the cloud
Philip Stehlik
 
Groovy & Grails - From Scratch to Production
Tal Maayani
 
Rails in the Cloud
iwarshak
 
Fast web development using groovy on grails
Anshuman Biswal
 
JavaOne 2008 - TS-5764 - Grails in Depth
Guillaume Laforge
 
Introduction to Grails 2013
Gavin Hogan
 
Cloud computing - an insight into "how does it really work ?"
Tikal Knowledge
 
Mastering Grails 3 Plugins - G3 Summit 2016
Alvaro Sanchez-Mariscal
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
nairakash2004
 
Guide - Migrating from Heroku to AWS using CloudFormation
Rob Linton
 
Build an app on aws for your first 10 million users (2)
AWS Vietnam Community
 
Aws Technical Day 2015 - Amazon API Gateway
aws-marketing-il
 
Spring Northwest Usergroup Grails Presentation
ajevans
 
Hosting a Rails App
Josh Schramm
 
Ad

Groovymag_May-2012

  • 1. Building Auto-scalable Cloud Based Applications using Grails 2.x and AWS Simple cloud based photo gallery application 12 • groovymag • volume four | issue seven | may, 2012 Building Auto-scalable Cloud Based Applications using Grails 2.x and AWS Simple cloud based photo gallery application By Igor Stelmashenko [email protected] https://plus.google.com/107671704413122133444/about Grails and AWS combination makes creation of auto- scalable web apps simple and fun. Learn how to create and deploy a simple photo gallery web application using SimpleDB, S3, SES and BeansTalk. The recent release of Grails 2.0 introduced a great number of very important features: a big performance boost, better error reporting, a database migration plugin and a great look and feel for mobile browsers are among my favorite ones. Grails was always one of the best frameworks for rapid web application development. Cloud services such as Amazon’s AWS complement it with auto-scalability. You can literally go from one to tens or hundreds of servers in a matter of minutes by using BeanStalk. You simply upload your application, and Elastic Beanstalk automatically handles the deployment details of capacity provisioning, load balancing, auto-scaling, and application health monitoring. You can add and remove capacity with a few clicks and it won’t cost you arm and a leg. This article will attempt to demonstrate it with a simple example. Let’s create a very simple photo sharing application and call it GGallery (sources available @ https://github.com/ thezaphod/ggallery). Let’s say you have a huge collection of photographs that you would like to share with your friends, family, and clients. Some of these photos might get posted on reddit.com or digg.com and you would like to make sure your application can handle your popularity as a photographer. You can try a running GGallery demo app @ http://ggallery.elasticbeanstalk.com/. Let’s re-create this application step by step. We will use Amazon Simple Storage Service (Amazon S3) for storing our images. S3 provides a simple web services interface that can be used to store and retrieve any amount of data. It gives any developer access to the same highly scalable, reliable, secure, fast, inexpensive infrastructure that Amazon uses to run its own global network of web sites. Let’s start with creating and AWS account at http://aws.amazon.com. Once the account is created, go to the AWS management console and create a ggallery bucket and upload a few of your images at https://console.aws.amazon.com/s3/home. Let’s create our grails application. Make sure you have Grails 2.X installed: $ grails create-app ggallery $ cd ggallery $ grails install-plugin aws $ grails install-plugin simpledb The AWS plug-in includes all the libraries required to take advantage of all AWS infrastructure. SimpleDB includes a JPA implementation for Amazon’s SimpleDB. Amazon SimpleDB is a highly available and flexible non-relational data store that offloads the work of database administration. We don’t need to learn SimpleDBAPIs since we are using a JPAimplementation.All object mapping will be done for us automatically. We only need to configure our application to give it permissions to access yourAWS account’s data. Find yourAWS security credentials from a menu at the top of a right corner of the AWS Management Console, as shown in Figure 2 (Next page). To configure theAWS plugins, open grails-app/conf/Config. groovy and append the configuration information below with your ownAccess Key ID and SecretAccess Key, as shown in Listing 1. access = ‘your access key here’ secret = ‘your secret key here’ grails { plugin { aws { // for S3, SES credentials { accessKey = access secretKey = secret } s3 { bucket = “ggallery” } } } simpledb { accessKey = access secretKey = secret domainNamePrefix = grails.util.GrailsUtil. environment dbCreate = ‘drop-create’ } } Listing 1: Grails AWS plugin configuration in Config.groovy [email protected]fi9yk8j05/08/201211:57:24AM
  • 2. Building Auto-scalable Cloud Based Applications using Grails 2.x and AWS Simple cloud based photo gallery application 13 • groovymag • volume four | issue seven | may, 2012 Figure 1: The GGallery application Figure 2: Access keys in the AWS Management Console [email protected]fi9yk8j05/08/201211:57:24AM
  • 3. Building Auto-scalable Cloud Based Applications using Grails 2.x and AWS Simple cloud based photo gallery application 14 • groovymag • volume four | issue seven | may, 2012 Let’s create Domain Objects and instruct GORM to store objects in SimpleDB: $ grails create-domain-class Email $ grails create-domain-class Photo $ grails create-domain-class Album Listing 5: The PhotoController implementation In PhotoController we use an injected by Grails and instantiated by plugin service aws to authorize access to S3 files, and then enumerate all images we previously uploaded and generate temporary public URL for the application. By default all files are stored securely on the S3 service. The view for the controller above simply loops through all images and displays them as thumbnails. package ggallery class Photo { String id String filePath String caption String url static mapWith = “simpledb” } package ggallery import org.jets3t.service.security.AWSCredentials import org.jets3t.service.impl.rest.httpclient. RestS3Service class PhotoController { // injected def aws // display image directory def index() { def c = new AWSCredentials( grailsApplication.config.grails. plugin.aws.credentials.accessKey, grailsApplication.config.grails. plugin.aws.credentials.secretKey) RestS3Service s3Service = new RestS3Service(c) def objs = s3Service. listObjects(“ggallery”, “”, “”) def album = new Album(title: params. id, url: request.getRequestURL(), photos: new HashSet()) objs.each() { def filePath = it.key def pUrl = aws.s3().on(“ggallery”). publicUrlFor(1.hour, filePath) def o = new Photo(filePath: filePath, caption: filePath, url: pUrl) } [album: album] } } package ggallery class Album { String id String title String url Email email static hasMany = [photos: Photo] static mapWith = “simpledb” } package ggallery class Email { String id String to String from String subject String text Album album static mapWith = “simpledb” } Listing 2: Photo class definition Listing 3: Album class definition Listing 4: Email class definition Let’s create a controller and view to display our images: $ grails create-controller Photo [email protected]fi9yk8j05/08/201211:57:24AM
  • 4. Building Auto-scalable Cloud Based Applications using Grails 2.x and AWS Simple cloud based photo gallery application 15 • groovymag • volume four | issue seven | may, 2012 Listing 6: Part of the view implementation Our application is ready to run. At this point we are able to view all our uploaded images from S3. Let’s add album creation capabilities and sending e-mail using Amazon Simple Email Service (Amazon SES). SES is a highly scalable bulk and transactional email-sending service for businesses and developers. Amazon SES eliminates the complexity and expense of building an in-house email solution or licensing, installing, and operating a third-party email service. Let’s create an Email service and Album controller to view album and send out the E-mail. $ grails create-service Email Listing 8: The AlbumController Before we can send email via Amazon SES, we need to verify that we own the address from which we’ll be sending email. I will verify my test account I created for this tutorial. You will need to verify you own address. Once you are ready to use Amazon SES to send email on production, you request production access. This will allow you to move from the sandbox environment to the production environment and begin sending email to any arbitrary e-mail account. $ grails aws-ses-verify-email > Enter the e-mail address to verify: ggallery@ intermobile.ca ... <g:each in=”${album.photos.sort{ it.filePath }}” var=”obj”> <div class=”album”> <div class=”thumb”> <a href=”${obj.url}”> <img SRC=”${obj.url}” width=”208” height=”158” BORDER=”0”></a> </div> <div style=”‚Ķ”> ${obj.caption} </div> <div style=”‚Ķ”> <input type=”checkbox” name=”add” value=”share” alt=”${obj.filePath}” onchange=”share(this.checked, this.alt)” /> share </div> </div> </g:each> ... package ggallery class AlbumController { // injected def aws def emailService def index() { } def create() { def msg = new Email(from: params.from, to: params.to, subject: params.subject, text: params.email, url: “${getSiteUrl(request)}/album/ show?id=”) msg.save() def album = new Album(title: params. title, photos: new HashSet(), email: msg, url: “${getSiteUrl(request)}/album/show?id=”) // create album session.images.each() { filePath -> def pubUrl = aws.s3().on(“ggallery”). publicUrlFor(1.hour, filePath) def f = new Photo(filePath: filePath, caption: filePath, url: pubUrl) f.save() album.photos.add(f) } album.save() String albumUrl = “${getSiteUrl(request)}/album/show?id=” + album. id msg.url = albumUrl msg.save() album.url = albumUrl album.save() msg.url = albumUrl msg.save() session.album = album redirect(action: “show”) // send e-mail emailService.send(msg) }package ggallery class EmailService { static transactional = false def send(email) { def mailId = sesMail { from “${email.from}” to “${email.to}” subject “${email.subject}” body “${email.text} n ${email.url}” } return mailId } } Listing 7: The EmailService $ grails create-controller Album [email protected]fi9yk8j05/08/201211:57:24AM
  • 5. Building Auto-scalable Cloud Based Applications using Grails 2.x and AWS Simple cloud based photo gallery application 16 • groovymag • volume four | issue seven | may, 2012 [AWS SES] Please check the email address ggallery@ intermobile.ca to verify it grails> aws-ses-list-verified-emails [AWS SES] 1) [email protected] The Album view gsp is not much different from the one we already defined to view all our images on S3. You will find the full source on github: https://github.com/thezaphod/ggallery/ blob/master/grails-app/views/album/show.gsp. Our application is ready and we can now deploy it on BeansTalk. To deploy your applications using AWS Elastic Beanstalk, you simply follow these steps: 1. Run $ grails war to create a standard deployable WAR file (Java Web Application Archive). 2. Upload your WAR file to Elastic Beanstalk using the AWS Management Console, the AWS Toolkit for Eclipse, the web service APIs, or the command line interface. 3. Deploy your application. Behind the scenes, Elastic Beanstalk handles the provisioning of a load balancer and the deployment of your WAR file to one or more Amazon EC2 instances running the Apache Tomcat application server. Within a few minutes you will be able to access your application at a customized URL (e.g. http://myapp. elasticbeanstalk.com/). Under the hood, Beanstalk is built using EC2 (Amazon Elastic Compute Cloud) instances as building blocks for scalable virtual infrastructure. All the complexity of managing a multitude of servers is hidden behind a simple web interface. Any of the actions performed with the web interface can be also scripted from the command line. You can test your running application on AWS at http://ggallery. elasticbeanstalk.com, and the full source for this application is on Github at https://github.com/thezaphod/ggallery. Let’s review what we did and why Cloud services such as Amazon AWS are a big deal. It allows you to create well architected, scalable software services utilizing best-of-the- breed technology and infrastructure. We’ve used Beanstalk, SimpleDB, SES and S3. Since these services are carefully designed and tested to scale, the architectural viability is guaranteed. This could be one of your critical advantages over solutions using old approaches. For example, S3 scales to a large enterprise needs for storage, Beanstalk for application hosting and SimpleDB for databases. There will be no big costly surprises once you attempt to scale it up. It also illuminates needs and the overhead system administration. It’s a self-serve, “get it when you needed it” in a matter of minutes deal. AWS is often called an infrastructure-as-a-service (IaaS) service. You basically have the same building blocks any IT of any mid-sized to large organization has without a big upfront investment and at the fraction of the costs of owning it. If you work for a small startup, this is a huge value proposition. Also, AWS doesn’t have a huge learning curve. In our example, we were able to take full advantage of SimpleDB using the same familiar to us technology – GORM. Tools like RazorSQL will allow you to navigate your stored data in SimpleDB as if it was a relational database. Have fun creating cool apps! [email protected]fi9yk8j05/08/201211:57:24AM