2011
10.14

I have been using CloudFoundry for my latest Grails demos at work because it’s incredibly easy and fun to use with Grails. This week I decided to deploy an app to Amazon Web Services though. I played with AWS Elastic Beanstalk, the AWS Java PaaS, when it first came out earlier this year and wrote a post about it. It was cool back then, but there were some minor issues. When I used it this week though, it was an awesome experience! So, I decided to write a post about it in case anybody else is just getting started with deploying Grails apps to AWS.

First, let’s define everything we are going to be using:

Under the covers, Elastic Beanstalk is actually using numerous different AWS services like EC2, S3 and Auto-Scaling, but this really doesn’t even matter to us! We get them all bundled together at no extra cost in an easy to use interface! This is in contrast to the Rails PaaS, Engine Yard, which also bundles numerous EC2 services together, but charges an additional 5 cents per hour for each EC2 instance. So, let’s dive in!

First thing we need to do is create a MySQL database in RDS.

  • Login to the AWS Console and go to the RDS tab
  • Click Launch DB Instance
  • Select MySQL
  • DB Engine Version: 5.1.57 (this is the default)
  • DB Instance Class: db.m1.small (start with smallest)
  • Multi-AZ Deployment: No (no reason to pay double when starting)
  • Allocated Storage: 5gb (smallest allowed)
  • DB Instance Identifier: sampleappinstance (need this for connection string)
  • Enter username and password
  • Click Continue
  • Database Name: sampleappdb (also needed for connection string)
  • Leave the port and availability zone as default
  • Click Continue
  • Leave backup options as default for now
  • Click Continue
  • Review and click Launch!

Here’s a screenshot of my sample RDS configuration (click for bigger version):

AWS RDS Configuration

Last thing on RDS is we need to modify the security group to allow connections to the MySQL database from Beanstalk. We will need two things:

  • AWS Account ID – Which you can find at the bottom Security Credentials page. Mine is a 12 digit number.
  • Elastic Beanstalk Security Group – Which will be elasticbeanstalk-default by default unless you change it

So, on the RDS tab, click on DB Security Groups under the side navigation. You will see one security group called default. Check the box for default and then look at the properties in the bottom pane. We’re going to add a new connection type to our default security group!

  • Connection Type: EC2 Security Group
  • Security Group: elasticbeanstalk-default
  • AWS Account ID: your id
  • Click Authorize

Now it’s time to prepare our Grails WAR file for deployment! There are three things we need to do before creating the WAR though:

  • Update production data-source
  • Update server url
  • Add dependency for MySQL

grails-app/conf/DataSource.groovy

...
production {
  dataSource {
    pooled = true
    dbCreate = "update"
    driverClassName = "com.mysql.jdbc.Driver"
    url = System.getProperty("JDBC_CONNECTION_STRING")
    dialect = org.hibernate.dialect.MySQL5InnoDBDialect
    properties {
      validationQuery = "SELECT 1"
      testOnBorrow = true
      testOnReturn = true
      testWhileIdle = true
      timeBetweenEvictionRunsMillis = 1000 * 60 * 30
      numTestsPerEvictionRun = 3
      minEvictableIdleTimeMillis = 1000 * 60 * 30
    }
  }
}
...

You’ll notice that I have dbCreate = update, but if you are using the database-migration plugin, you would set this to “none” and configure Grails to automatically run your migrations during start-up. I’m just keeping it simple with “update” for this example though.

Also, we set the URL to JDBC_CONNECTION_STRING so that we don’t have to store the username and password in this file which means it can safely be stored in GitHub (or whatever version control you’re using).

grails-app/conf/Config.groovy

...
production {
  grails.serverURL = "http://www.sampleapp.com"
...
}
...

You will need to register a URL somewhere and then point your name-servers to AWS Route 53 which I will discuss later.

grails-app/conf/BuildConfig.groovy

...
dependencies {
  runtime 'mysql:mysql-connector-java:5.1.16'
}
...

Next, we need to package our Grails WAR and deploy to Beanstalk!

grails prod war

  • Click on the Beanstalk tab in the AWS Console
  • Click on Create New Application
  • Application Name: sampleapp
  • Browse to your WAR file (sampleapp-0.1.war)
  • Enter in whatever you want for the description, url, etc.

Here’s a screenshot of my sample Beanstalk configuration (click for bigger version):

AWS ElasticBeanstalk configuration for sampleapp

We will get an error when Beanstalk tries to start the application though because remember we said we wanted a system property called JDBC_CONNECTION_STRING to be used for the MySQL URL. So, we need to add this. So, on the Beanstalk tab expand the Environment Details for the sampleapp application and click on Edit Configuration. Then click on the Container tab. Scroll down to where you see JDBC_CONNECTION_STRING and enter in the following:

jdbc:mysql://sampleappinstance.AAAAAA.BBBBBB.rds.amazonaws.com:3306/sampleappdb?user=CCCCCC&password=DDDDDD

  • AAAAAA: the value for your instance, which you can get from the RDS tab
  • BBBBBB: correct region, which you can get from the RDS tab
  • CCCCCC: username, whatever you entered during RDS instance creation/li>
  • DDDDDD: password, whatever you entered during RDS instance creation

Then restart the application in Beanstalk. Now the moment of truth! Go to the url for the application and make sure it works! For example: http://sampleapp-prod.elasticbeanstalk.com was the one I used. Hopefully everything works and the app is successfully configured in Beanstalk using RDS! If not, you’ll need to go back and double check the configuration.

Now the final touch! Let’s configure our own domain because we don’t want users going to an elasticbeanstalk.com url for our app! There was a problem with Route 53 earlier this year where you couldn’t route a root domain to an Elastic Load Balancer, but this is fixed now! So, we can use Route 53 to host our domain as well as make sure the root domain and the www subdomain are sent to our application on Beanstalk.

There isn’t an official interface from Amazon for Route 53, but Interstate 53 will do the job! Go to https://interstate53.com. You can see we need two things to login: Access Key and Secret Key. We can get these from the AWS Security Credentials page. Once logged in, click on Add New Domain and enter your domain. On the domain page, note down the 4 name server records listed and enter those in at your registrar. We want to point the domain to Route 53′s name servers at wherever the domain is registered.

Now we are going to create two records for the domain: Alias Record to ELB and Alias CNAME Record.

Alias Record to ELB

  • Goto EC2 tab in AWS console
  • Under My Resources, click on 1 Load Balancer
  • Select the load balancer and look at the properties below
  • Copy the Hosted Zone ID and the DNS Name listed for “A Record” to a text file
  • Back in Interstate53, click on your domain and then Add Record
  • Select Alias Record to ELB
  • Leave Name blank and type as A
  • Put your Hosted Zone ID and DNS Name for the load balancer into the respective fields
  • Click Save

Alias CNAME Record

  • Click Add Record again
  • Select Alias CNAME Record
  • Enter www for Alias
  • Enter your load balancer DNS for Canonical Name
  • Click Save

Back on the domain overview page, click on Accept Changes. Then back on the main page, hover over the Actions section and click Push (to send the changes to AWS). If everything works, the root domain and www subdomain are now pointed at the Elastic Load Balancer! That’s all there is to it! You can certainly change lots of configuration items in RDS and Beanstalk after your app is deployed like creating read-replicas of MySQL and setting the minimum number of Tomcats to more than one, but this obviously all depends on what resources your Grails app needs (and how much you want to spend, ha!)

I hope you enjoyed reading my post on Grails on AWS! Please leave a comment if you have any questions or feedback about this post!

2011
09.23

In my previous post, I talked about Polyglot programming in Grails. As I mentioned in that post, there are plugins for Clojure and Scala, but not for Ruby or Python. So, today I thought I would tackle one of those by creating a new Grails plugin for Ruby! It was really easy to integrate JRuby (the Ruby implementation for the JVM) with Grails and I think the plugin works pretty good so far! So, keep reading to see how I created the plugin as well as a demonstration of how to use the plugin!

I decided that I should do things the right way this time and start with some test cases and then implement the code to satisfy those tests (test-driven-development). So, lets create a sample app with a test class and a controller. I’m using an integration test instead of a unit test because as you’ll see later, I’m actually going to be doing some meta-programming and need access to the entire Grails environment in the test for my dynamic “ruby” method to work.

  • grails create-app grails-ruby-sample
  • cd grails-ruby-sample
  • grails create-controller home
  • grails create-integration-test grails.ruby.sample.HomeController

These are the only Groovy files we’ll need in the sample app. The only other thing will be a Ruby file which we’ll add later. Here’s the tests:


// test/integration/grails/ruby/sample/HomeControllerTests.groovy
package grails.ruby.sample
 
import static org.junit.Assert.*
import org.junit.*
 
class HomeControllerTests extends GroovyTestCase {
  def dayOfWeek
 
  @Before
  void setUp() {
    dayOfWeek = new Date().format("EEEE")
  }
 
  void testHi() {
    def controller = new HomeController()
    controller.hi()
    assertEquals controller.response.contentAsString, "Hi Bobby! Today is $dayOfWeek.".toString()
  }
 
  void testBye() {
    def controller = new HomeController()
    controller.bye()
    assertEquals controller.response.contentAsString, "Bye Bobby! Today is $dayOfWeek.".toString()
  }
}

As you can see, we are just testing the output of two Grails controller actions. One says hi and one says bye. This would be very easy to implement in straight Groovy, but we’re actually going to have the controller call out to Ruby for the implementation! Here’s the controller:


// grails-app/controllers/grails/ruby/sample/HomeController.groovy
package grails.ruby.sample
 
class HomeController {
  def hi() {
    ruby.put('name', 'Bobby')
    ruby.put('greeting', 'Hi')
    render ruby.eval('greet($name, $greeting)')
  }
 
  def bye() {
    ruby.put('name', 'Bobby')
    ruby.put('greeting', 'Bye')
    render ruby.eval('greet($name, $greeting)')
  }
}

So now we have our sample app all setup to test! The first thing you are probably wondering though is where the heck did that “ruby” property come from, right? To explain that, let’s switch gears and start looking at the source for the plugin (grails-ruby)! There’s really only four parts:

1) grails-app/conf/BuildConf.groovy: We need to add a runtime dependency for JRuby.

dependencies {
  runtime 'org.jruby:jruby:1.6.4'
}

2) RubyGrailsPlugin.groovy: We need to implement onChange and doWithDynamicMethods for evaluating Ruby code, automatically re-loading when a Ruby file changes and inserting the “ruby” property into all Groovy classes via meta-programming.

def onChange = { event ->
  ScriptEngine engine = new ScriptEngineManager().getEngineByName("jruby")
 
  def source = event.source
  if(source instanceof FileSystemResource && source.file.name.endsWith('.rb')) {
    source.file.withReader { reader ->
      engine.eval(reader);
    }
  }
}
 
def doWithDynamicMethods = { ctx ->
  ScriptEngine engine = new ScriptEngineManager().getEngineByName("jruby")
 
  def rubyFiles
  if(application.warDeployed) {
    rubyFiles = parentCtx?.getResources("**/WEB-INF/ruby/*.rb")?.toList()
  } else {
    rubyFiles = plugin.watchedResources
  }
 
  rubyFiles.each {
    it.file.withReader { reader ->
      engine.eval(reader)
    }
  }
 
  application.allClasses*.metaClass*."getRuby" = {
    return engine
  }
}

3) scripts/_Events.groovy: We need to use the eventCompileStart event to copy Ruby files over to the destination directory (WEB-INF/ruby).

eventCompileStart = {
  def rubyDestDir = "${grailsSettings.projectWarExplodedDir}/WEB-INF/ruby"
  ant.mkdir dir: rubyDestDir
  ant.copy (todir: rubyDestDir) {
    fileset(dir:"${basedir}/src/ruby", includes:"*.rb")
  }
}

4) scripts/_Install.groovy: We need to create a directory for applications using the plugin to put Ruby files in (src/ruby).

ant.mkdir(dir:"${basedir}/src/ruby")

And that’s really all there is to it! You can view the plugin source on GitHub here. So, now back to our sample application (grails-ruby-sample)! Let’s install the plugin, create a Ruby file that we will use from the controller, implement the Ruby code to satisfy our Groovy test cases and test our app!

  • grails install-plugin ruby
  • touch src/ruby/ruby_hello_world.rb


// src/ruby/ruby_hello_world.rb
class RubyHelloWorld
  def create_greeting(name, greeting)
    time = Time.new
    day = time.strftime("%A")
    "#{greeting} #{name}! Today is #{day}."
  end
end
 
def greet(name, greeting)
  hello_world = RubyHelloWorld.new
  hello_world.create_greeting(name, greeting)
end

  • grails test-app

And that’s it! The two integration test cases for our sample app should pass. It might take awhile to download the JRuby libraries the first time testing or running after you install the plugin though.

The source code for the plugin and sample app are located on GitHub and the plugin is documented in the Grails plugin portal:

I used Jeff Brown’s Clojure plugin as a guide for creating this Ruby plugin. I have set the version for this first release of the plugin to 1.0.M1 which simply means it’s a milestone release and not ready for production yet. I hope to have a final 1.0 release in the near future after I get some feedback on the plugin as people test it out. I hope you enjoyed reading this post about Grails Ruby!

2011
09.21

I have been playing around with using different JVM languages in Grails lately. For example, Clojure is really easy to integrate into Grails via the plugin. The simple fact that you can do this in Grails by just installing one little plugin is pretty cool! So, I decided it would be fun to create a Grails app that uses as many languages as possible, ha! There’s absolutely no good reason to do this other than it’s kind of fun!

There aren’t any Ruby or Python plugins for Grails yet, so I just add them as dependencies manually. I’m actually using JRuby and Jython though, which are implementations of these languages specifically for the JVM. For JavaScript, Rhino which comes bundled with JDK 6. The end goal is to have one Grails controller (a Groovy class) that uses Ruby, Python, JavaScript and Clojure (note at bottom about why Scala wasn’t included).

First, we need to setup our polyglot Grails application!

  • grails create-app polyglot
  • cd polyglot
  • grails install-plugin clojure


// grails-app/conf/BuildConfig.groovy
dependencies {
  runtime 'org.jruby:jruby:1.6.4'
  runtime 'org.python:jython-standalone:2.5.2'
}

Then we need to create three Grails files (a controller, unit test and integration test). Why an integration test and unit test? Well, this is simply because it is not possible (at least right now) to test Clojure code via the plugin in unit tests. There is a property (clj) injected into Grails artifacts (our controller in this case), but it only works in integration tests. The rest of the languages can be tested in a unit test though.

  • grails-app/controllers/polyglot/TestController.groovy
  • test/unit/polyglot/TestControllerUnitTests.groovy
  • test/integration/polyglot/TestControllerIntegrationTests.groovy

Next, we need a simple problem we want to try out in all languages. I’m a math nerd, so I’m simply going to make sure that the value of PI is the same in all languages. Here’s my controller:


package polyglot
import javax.script.*
class TestController {
  def javascript() {
    def engine = new ScriptEngineManager().getEngineByName("JavaScript")
    render engine.eval("Math.PI")
  }
  def ruby() {
    def engine = new ScriptEngineManager().getEngineByName("jruby")
    render engine.eval("Math::PI")
  }
  def python() {
    def engine = new ScriptEngineManager().getEngineByName("python")
    engine.eval("import math")
    render engine.eval("math.pi")
  }
  def clojure() {
    render clj.pi
  }
}

As you can see, I’m using the ScriptEngine class that comes with Java 6 to invoke the Ruby, Python and JavaScript languages. You could just as easily have put the code in separate Ruby, Python, JavaScript files, but I’m just keeping it simple for this example. The only real difference is that for Python you need to import math first. The Clojure implementation is in a separate file because the plugin automatically adds a folder under src and hooks into Grails events to compile. Here’s the Clojure code:


; src/clj/pi.clj
(ns grails)
(def pi Math/PI)

We can certainly test the controller by viewing these actions in a browser to make sure all the languages are working, but the whole point is to make sure they are all the same, right? So, I’m going to write actual tests that compare the value returned from the actions for each language against the value of PI in Groovy! Here’s my unit tests:


package polyglot
@TestFor(TestController)
class TestControllerTests {
  void testJavaScript() {
    controller.javascript()
    assertEquals response.text, Math.PI.toString()
  }
  void testRuby() {
    controller.ruby()
    assertEquals response.text, Math.PI.toString()
  }
  void testPython() {
    controller.python()
    assertEquals response.text, Math.PI.toString()
  }
}

And here’s the integration test for Clojure:

package polyglot
class TestControllerIntegrationTests extends GroovyTestCase {
  void testClojure() {
    def test = new TestController()
    test.clojure()
    assertEquals test.response.contentAsString, Math.PI.toString()
  }
}

And there we have it! A Grails application that calculates PI in Clojure, Ruby, Python and JavaScript as well as ensures PI in these languages is the same as PI in Groovy! Hope you enjoyed reading!

As a side note, there also is a Scala plugin for Grails, but I unfortunately could not get it to work with Grails 2.0.0.M2. I keep getting the following error when I try to compile Scala source code via the plugin.

Could not compile Scala sources: BuildException: Compile failed because of an internal compiler error (object scala not found.)

If anybody who has successfully used the Scala plugin with Grails 2.0 has any suggestions for what I might be doing wrong, please leave a comment.

2011
08.01

Grails Contributors

Have you played around with Cloud Foundry yet? I looked at it when it was first released a couple months ago, but hadn’t really used it since… until now! I’ve always thought that the Rails Contributors site is kind of cool, ha! So, I decided I should start something similar called “Grails Contributors” and use it as a way to learn about deploying to Cloud Foundry!

Just like Rails, Grails uses GitHub for source code management. So, I looked at the source code for the Rails version and it looked pretty simple the way it was calling the GitHub API. GitHub is actually in the process of upgrading to a new V3, but V2 is still active and V3 didn’t have the specific REST call I needed, so I decided to use V2 for now. I developed an initial basic version, put the source on GitHub and deployed to Cloud Foundry. Then I announced on the Grails mailing list that any other partners-in-crime are welcome to join!

To my delight, I’ve had two people submit pull requests! François-Xavier Thoorens from France and Felipe Carvalho from Brazil! François has been a rockstar and has probably written more lines of code in the application than I have right now! He designed the new interface and also had the great idea to expand it beyond just the Grails source and documentation by including Grails plugins! We have a good start, but there’s still plenty of work to be done! I also created a JIRA to see if we can get the CNAME http://contributors.grails.org like the rails version too! (Not sure if this is going to happen or not though)

I started out with the latest build of 2.0.0 and MySQL, but François and I later decided that we wanted to try out MongoDB and ran into some issues with the MongoDB plugin with 2.0.0. So, we switched back to 1.3.7 for now. The MongoDB plugin makes it incredibly easy to use Mongo with Grails!

Here’s the current running version of the site: http://grails-contributors.cloudfoundry.com and here’s the source-code on GitHub: https://github.com/bobbywarner/grails-contributors

So, if you have any ideas for ways to make it better, feel free to join us! All you need to run it locally is Grails 1.3.7 and MongoDB. I’m licensing all the code under Apache 2.0! So feel free to go fork the repo on GitHub and send me a pull request!

2011
07.08

I’m working on a project right now that will use lots of addresses and the locations around them. So, I needed to start playing around with geocoding!  I’m planning on using Google Maps for all my mapping needs, so it made sense to use the Google Maps Geocoding API as well (there are certainly other ones you can use though) and I put together a quick Grails application to show a sample of the type of stuff I’m doing. You can see all the code for this sample Grails app (geocoder) on GitHub.

To see what’s really happening, take a look at the GeocodeService class.  This is where I’m taking the query from the controller and sending it to Google requesting either XML or JSON.  I then take specific parts of the result and put them in a map for easy access in my view.  I’m also using the new groovy.json.JsonSlurper class that is part of Groovy 1.8.  It makes working with JSON really easy!  Here’s an excert from that class:


def queryForJSON(String query) {
  def config = ConfigurationHolder.config
  String configUrlJSON = config.googleapi.url.json
  def urlJSON = new URL(configUrlJSON + removeSpaces(query))
  def geoCodeResultJSON = new JsonSlurper().parseText(urlJSON.getText())
  def jsonMap = [:]
  jsonMap.query = query
  jsonMap.lat = geoCodeResultJSON.results.geometry.location.lat[0]
  jsonMap.lng = geoCodeResultJSON.results.geometry.location.lng[0]
  jsonMap.address = geoCodeResultJSON.results.formatted_address[0]
  return jsonMap
}

Here’s the unit test for this service method:


void testQueryForJSON() {
  def result = service.queryForJSON("Times Square")
  assert "40.75659" == result.lat.toString()
  assert "-73.98626" == result.lng.toString()
  assert "Theater District - Times Square, New York, NY, USA" ==
         result.address
}

Pretty simple to do this type of stuff with Groovy! Thanks for reading and let me know if you have any suggestions for working with geocoding!

2011
06.29

Have you played around with Grails Resources yet?  I just started looking at the plugin tonight and turns out it’s pretty slick!  So, I thought I would write a post to document the steps I took to get up and running!

First, you will want to grab the latest source for Grails 2.0.0.BUILD-SNAPSHOT:

  • git clone https://github.com/grails/grails-core.git
  • cd grails-core
  • ./gradlew install

Then you will want to create a new app and install the relevant plugins.  The resources plugin is installed by default with Grails 2.0, so you don’t have to worry about that one, but you will want to install the zipped-resources and cached-resources plugins.  Also, unless you’ve been living under a rock in the web development world, you know that dynamic stylesheet languages are all the rage right now, ha!  In Ruby on Rails 3.1, they will actually bundle SASS by default.  SASS looks pretty good but there currently isn’t a plugin that works with Grails resources, so I’ve started using the LESS plugin.  LESS looks just as good as SASS as far as I can tell and since it works with Grails resources, it’s definitely the way to go!  So, let’s dive in!

  • cd ~/workspace (or wherever you keep your code)
  • grails create-app sampleapp
  • cd sampleapp
  • grails install-plugin zipped-resources
  • grails install-plugin cached-resources
  • grails install-plugin lesscss-resources
  • grails install-plugin jquery-ui (jquery is installed by default)

Now that we have all the plugins installed, we need to create our LESS, CSS and JavaScript files.  So, let’s create these files.

  • sampleapp/web-app/less/main.less
  • sampleapp/web-app/css/main.css
  • sampleapp/web-app/js/main.js

And put this in the main.less file:


@color: #FF0000;
   
h1 {
   color: @color;
}

You can see that we are actually defining a variable in our CSS called color and using this variable in h1. This is obviously pretty basic programming, but until frameworks like SASS and LESS came along, this was not possible in CSS, so it’s actually pretty sweet! I love being able to define colors at the top of a LESS file and use variables throughout the rest of the file. It makes it so much easier to switch colors later on. No more find-and-replace to change color codes, ha!

You might be wondering why we created a LESS file and a CSS file though, right?  Well, I actually did this just for demonstration purposes to show that you can still obviously use regular CSS files while you are using LESS.  I’ll probably use LESS for all my styles going forward though.  Next we need to add a config block for resources.  Add the following to the bottom of sampleapp/grails-app/conf/Config.groovy


grails.resources.modules = {
   core {
      dependsOn 'jquery, jquery-ui'
      resource url:'/js/main.js'
      resource url:'/css/main.css'
      resource url:'/less/main.less',attrs:[rel: "stylesheet/less", type:'css'], bundle:'bundle_core'
   }
}

This is where the power of the Grails resources plugin really starts to show! In this resource module, we’re saying we depend on jquery and jquery-ui, so it will include these as well anywhere we say we require the module “core” in our app. Then we need to update our layout as per the resources instructions, so create a basic layout that looks like this:


<!doctype html>
<html>
   <head>
      <title><g:layoutTitle default="Sample App"/></title>
      <r:layoutResources/>
   </head>
   <body>
      <g:layoutBody/>
      <r:layoutResources/>
   </body>
</html>

And then this is how we include our resources module in a GSP.


<!doctype html>
<html>
   <head>
      <meta name="layout" content="main"/>
      <r:require module="core"/>
   </head>
   <body>
      <h1>Sample App</h1>
   </body>
</html>

If you look at the HTML source for the page, you’ll see that the resources plugin is renaming the files to hashes of the file so that it knows when the files have changed.  If everything is working correctly, the Sample App heading text on the page will show up in red as per our LESS style and if you view the generated CSS, you’ll see that the color code has been added in for the variable.  This is just a basic example, so make sure you take a look at the LESS website to get a feel for everything you can do with a dynamic stylesheet language.

So there we have it!  Our resources are zipped, cached and we’re using a dynamic stylesheet language in Grails 2.0!  I hope you enjoyed reading this post and please let me know if you have any feedback on the steps I used to get going with these plugins.

2011
06.21

Did you know that you can have a complete modular enterprise application up and running in under 5 minutes with Grails? The architecture will be a lot more flexible and maintainable than any “Enterprise Java” structure with Ant or Maven too!

First things first, how many different modules should an application have? Well, every application probably needs three essential things these days: website, mobile website and API. Wait, why do you need an API if you don’t necessarily have any plans of sharing data? Well, the answer is you might need native Android and iPhone apps in the future, so you might as well plan for them right away. The HTML5 frameworks are getting pretty good though! Take a look at Sencha Touch if you haven’t yet as it’s pretty cool!   So why can’t you just use one project for the API and the website?  Well, I don’t recommend having a controller that returns JSON or HTML based on the request. It seems cluttered to me plus you might want to return more or less data given the target and have a completely different security setup for each (basic, digest or token for API vs forms for web).  Also, versioning the API is a lot easier if it’s separate from the website. Plus as you’ll see in a bit, it’s really easy with Grails to separate out the API into a separate project and reuse code.

First, create a parent folder for the entire application. Then create three separate Grails applications in this parent folder.

  • grails create-app sampleapp-web
  • grails create-app sampleapp-api
  • grails create-app sampleapp-mobile

Next, create a Grails plugin for the core part of the application. This is where you’ll put all reusable code for your application like domain classes and services.

  • grails create-plugin sampleapp-core

Now we need to set a reference to our plugin in each of the three Grails applications we created. This is slightly different from installing regular Grails plugins. Since this plugin is going to be changing a lot as you develop the application, you don’t want to be constantly packaging and installing the plugin into each of the three apps. So, instead add this line to the end of grails-app/conf/BuildConfig.groovy for each of the three (web, api and mobile).

  • grails.plugin.location.’sampleapp-core’ = “../sampleapp-core”

Now you can add a class to “core” at any time and it’s automatically available to all three projects! You never have to compile the core plugin, but rather when you run or test any of the three main apps, it will automatically pick up changes made in core. Pretty slick, huh! We’re not done yet though! You obviously want to test all three at the same time, right? Ha! Ok, maybe not, but I do for some reason! Plus I like to run other stuff on 8080 anyway, like Jenkins for example, so let’s add this line to grails-app/conf/BuildConfig.groovy so that they run on different ports and there’s no conflict on port 8080.

  • sampleapp-web/grails-app/conf/BuildConfig.groovy:
    • grails.server.port.http = 8081
  • sampleapp-api/grails-app/conf/BuildConfig.groovy:
    • grails.server.port.http = 8082
  • sampleapp-mobile/grails-app/conf/BuildConfig.groovy:
    • grails.server.port.http = 8083

Next, I’m never nearly as good of programmer as I pretend to be, so I always add the code review plugin!

  • grails install-plugin codenarc

Finally, the last thing actually has nothing to do with setting up an application, but rather is just cause I’m kind of lazy, ha! Let’s shorten the typing required for run-app and test-app scripts. This may seem really trivial, but think about how many times you’ll type these commands, makes sense to make them as short as possible, doesn’t it?  Plus, it will also show how cool our setup is by being able to reuse scripts across all four Grails projects! You could also create scripts that are available to all Grails projects on your computer, but I think it’s better to keep each application completely independent.

Run the following command while in the core plugin (sampleapp-core):

  • grails create-script ra
  • grails create-script ta

This will create two files in sampleapp-core/scripts.  Erase everything from these two files and add this:

  • sampleapp-core/scripts/Ra.groovy: includeTargets << grailsScript(“RunApp”)
  • sampleapp-core/scripts/Ta.groovy: includeTargets << grailsScript(“TestApp”)

With these two scripts setup in core, you can now simply execute grails ra or grails ta instead of grails run-app and grails test-app in any of the four Grails projects!

Well, I hope you enjoyed my Grails Setup article!  It certainly is a better setup than any crazy stuff I used to do with Ant or Maven!  Let me know if you have any suggestions for ways to improve it.  Happy coding!

2011
06.20

Ok, I have to admit that the title is a little misleading…  This isn’t a traditional “Grails 101″ where you learn how to install the framework and create twitter, ha! This is instead an article about what it means to get started contributing back to the Grails community. I just started doing this a couple months ago, so I thought it would be interesting to blog about the steps required to do so for anyone else that wants to start contributing!

So, how do most people get started with Grails?  They go to grails.org and download the ZIP binary, right?  Sure, this is good, but if that’s all you do then you are kind of missing out.  I would argue that starting out with any new technology, the first thing you should do is build it from scratch!  Wait, what?  Why waste your time building from scratch?  The reason is you need to understand what’s happening under the hood to really become an expert so you can make modifications if needed for your application.  I’m certainly not an expert on Grails (yet!) but I have definitely increased my knowledge about the framework and become a better Grails developer by building Grails from source, examining the source code and contributing patches to the documentation!

So, let’s dive in!

  1. Login to GitHub (create an account if you don’t have one)
  2. Navigate to Grails-Core and Grails-Doc and fork both of them. You should now have your two forks similar to these Bobby Warner Grails-Core, & Bobby Warner Grails-Doc for your account
  3. Next you want to create your local copy (a clone in Git terms) and you can do this by executing these two commands:
    • git clone git@github.com:youraccount/grails-core.git
    • git clone git@github.com:youraccount/grails-doc.git
  4. There’s three sets of repositories now, the original ones at github.com/grails, your forks at github.com/youraccount and your local copies. We already have a reference from local to the GitHub forks, but we also want a reference from local to the originals so that we can pull in updates that are made by other users since we forked.
    • cd grails-core
    • git remote add upstream git://github.com/grails/grails-core.git
    • git fetch upstream
    • cd ../grails-doc
    • git remote add upstream git://github.com/grails/grails-doc.git
    • git fetch upstream
  5. Now we have our local repositories all set and it’s time to build them!
    • cd ../grails-core
    • ./gradlew install
    • cd ../grails-doc
    • ./gradlew docs  (Or  ./gradlew docs -Dgrails.home=../grails-core)
    • Set your $GRAILS_HOME to the grails-core directory
    • grails create-app newapp
  6. Now we’re rocking!  We have our own local copies of the Grails source-code and the documentation and are ready to start making our own modifications! We also created a new Grails application using our own local version of Grails we just compiled.
  7. Now it’s time to contribute something back to the community! First, we’ll have to find something to change. Then commit the change to our local repository and fork. Finally, we’ll open a pull request on the original Grails repository.  The example I’ll use just to explain was a simple change to the docs I made and opened a pull request for: https://github.com/grails/grails-doc/pull/46. You can see when clicking on that link that it is marked as “closed” status which means that someone on the core team (Burt Beckwith in this case) reviewed the pull request and committed to the master branch (my patch was “accepted” by the Grails team to the docs).  So, once you’ve found something you want to change, this is what you need to do:
    • git branch your-change-name
    • git checkout your-change-name
    • Edit the files you want to change 
    • git commit -a -m ‘Your Commit Message’
    • git push origin your-change-name
    • Then back on GitHub, click Pull Request to send it off for review! If it’s good, hopefully your pull request will be committed and if not, hopefully you’ll be given some comments about why not, ha!
  8. Lastly, you’ll want to make sure you keep your copies (remember there’s two, the GitHub fork and your local one) up to date with the original.
    • cd ../grails-core
    • git checkout master (if you made a branch here in step 7)
    • git fetch upstream
    • git merge upstream/master
    • git push origin master
    • ./gradlew install
    • cd ../grails-doc
    • git checkout master (if you made a branch here in step 7)
    • git fetch upstream
    • git merge upstream/master
    • git push origin master
    • ./gradlew docs  (Or  ./gradlew docs -Dgrails.home=../grails-core)
  9. Then just keep an eye on the GitHub pull request to see if it’s accepted!

Now that you’ve done a basic branch and pull request, it’s time to take a look at JIRA and see if you can tackle any open issues (or start opening your own!).  I personally haven’t solved too many issues yet other than some simple bug fixes, but hope to start contributing more in the future! 

I hope you enjoyed my “Getting Started With Grails” article.  Please let me know if you have any feedback or suggestions about the steps I outlined for getting started contributing back to Grails!

2011
04.11

The Spring-Security plugins for Grails are awesome! They got me 90% of the way there for pretty much everything I needed to do from a security standpoint for Mural Mate. One requirement that I needed to code my own solution for though was the desire to only allow the particular Owner (i.e. person who created it) update that League, Team, Classified, etc.  If it was just Admins it would have been incredibly easy by just using a new Role (ROLE_ADMIN), but obviously I want the Team Owner, League Owner, Classified Owner, etc to be able to update their own stuff, but not anybody else. I couldn’t use a new role (i.e. ROLE_OWNER) for this because a user might be an owner for one League, but obviously not all of them.  Also, Admins need to be able to update anything in the system. So, I dove in and this is what I came up with!

I knew I was going to need two things, a taglib and a service.  The taglib is needed so that I can hide the edit and delete buttons from everybody except the particular owner and admins in GSPs and the service is used to abstract the logic for controllers.  Let’s start with the service first:


/**
* Determines whether the current user
* has the authority to edit the instance
*
* @attr instance the instance to evaluate
**/
boolean hasModifyAuth(instance) {
  if (SpringSecurityUtils.ifAnyGranted("ROLE_ADMIN")
      || instance.owner.id == springSecurityService.getCurrentUser().id) {
    return true
  } else {
    return false
  }
}

This service method is pretty simple, but does the trick! It checks if the current user is an admin or the owner for whatever instance is passed to it (all my domain classes that I want to do this with have an owner property of type User).  Onto the taglib:


static namespace = "mm"
 
/**
* Renders the body if user has authority
*
* @attr value REQUIRED the field value
*/
def ifModifyAuth = { attrs, body ->
  def instance = assertAttribute("value", attrs, "ifModifyAuth")
  if (SpringSecurityUtils.ifAnyGranted("ROLE_ADMIN")
      || instance.owner.id == springSecurityService.getCurrentUser().id) {
    out << body()
  }
}
  
protected assertAttribute(String name, attrs, String tag) {
  if (!attrs.containsKey(name)) {
    throwTagError "Tag [$tag] is missing required attribute [$name]"
  }
  attrs.remove name
}

Once again pretty simple, but works perfectly! I copied the assertAttribute method idea from the Spring-Security-Core plugin and with the REQUIRED in the JavaDocs, SpringSource Tool Suite auto-completes the value attribute for the tags!  Then I just do something like this in my GSPs:


<mm:ifModifyAuth value="${teamInstance}">
  ... edit and delete links ...
</mm:ifModifyAuth>

And this in my controller that I wanted to restrict modify access:


def beforeInterceptor =
  [action:this.&auth,only:['update', 'delete', 'edit']]
 
def auth() {
  def instance = Team.get(params.id)
  if (instance) {
    if (!muralMateSecurityService.hasModifyAuth(instance)) {
      flash.message = "You do not have access to modify this instance"
      redirect(action: "list")
      return false
    }
  } else {
    flash.message = "Instance not found"
    redirect(action: "list")
    return false
  }
}

And there we have it! A reusable taglib for my views and service for my controllers implementing my custom authorization requirements!

2011
04.11

Mural Mate Update

I’ve been working on Mural Mate for just about two weeks now, so I thought it was time to provide an update on my progress! Some basic stats about the app so far: 13 domain classes, roughly 4000 lines of code (Groovy & GSPs) and using 9 Grails plugins.  The initial code-base is focused around five main areas: Users, Leagues, Teams, Games and Classifieds. Every team has a manager and every league has an owner. Each team can belong to a league, but doesn’t have to. All games must belong to a team and all classifieds must belong to a game. Users can belong to or manage as many teams as they want. The whole concept behind classifieds is to allow team managers to post when they need a sub for any particular game.  I might expand on this after the initial release if it becomes popular to allow users to post the opposite type of classified too (availability to play on a particular night for sports they are interested in), but not for the initial release.

I’ve really enjoyed using the Spring-Security plugins (spring-security-core and spring-security-ui). The entire authentication and authorization process (registration, login/logout, forgot password) is all implemented using these plugins. I also have really enjoyed the great Groovy support in SpringSource Tool Suite 2.6.  I’ve finally abandoned TextMate, ha! :) I’m not sure if it will make the initial release, but integrating with Spring-Social is still on my radar!

All along I’ve been planning to use AWS BeanStalk for hosting the application, but there is an interesting announcement being made tomorrow from SpringSource that could potentially change my mind. Whatever they announce, I will certainly weight the pros/cons of it against BeanStalk before I make my decision. I also have all the email accounts setup with Google. I’ll probably have to buy a business account to avoid the 500 emails per day limit of the free ones though.

So, to wrap up, I’ve made lots of progress and hope to have an initial version for beta-users to tryout sometime in May!

Switch to our mobile site