2012
01.09

Have you used CoffeeScript yet? I just started playing with it and so far I think it’s great! In this screencast, I walk through how to use CoffeeScript in a Grails 2.0 application by building a simple “continuous-scrolling” page. Please let me know in the comments if you find the screen-cast valuable or not!

The source-code for this screencast is available on GitHub: https://github.com/bobbywarner/grails-coffeescript-demo

This screencast was inspired by Ryan Bates’ RailsCasts Episode #114. I borrowed some of his excellent CoffeeScript example code.

2012
01.05

Do you hate reading? Well today is your lucky day because instead of reading a post, you can watch my first ever Grails screen-cast! It’s definitely a little rough around the edges though and you’ll have to watch it full-screen otherwise the text will be too small.

The topic is “Jumping into Grails 2.0″ using the spring-security-core and resources plugins as well as some unit testing. Please let me know in the comments if you find the screen-cast valuable or not.

2011
12.30

In my last post, I introduced using Stripe with Grails to process credit cards. I guess I should have waited to write that post though because today I made it a lot easier, ha! :)

As of the 1.0.M6 release, the plugin has a new tag library that takes care of all the JavaScript and credit card input fields for you! This is all that’s required now to create the form:

A couple notes about this code compared to my previous post’s code:

  • You no longer need to declare the resource module stripe, the plugin takes care of this.
  • You no longer need to worry about setting the publishableKey, the plugin takes care of this now too.
  • <stripe:script formName=”payment-form”/> is required to setup all the JavaScript. The formName attribute needs to match the name attribute on your <g:form> tag.
  • <stripe:creditCardInputs cssClass=”form-row”/> is optional if you want the plugin to create the credit card fields (number, cvc, exp-month & exp-year). The cssClass attribute is what class you want the plugin to put for the div tag surrounding each credit card field. You don’t have to use this though and can include these fields manually in your form if you’d prefer.

This will all be covered in the plugin documentation which will be done with the 1.0 final release. Thanks to those who already provided feedback! Please let me know what you think of these new updates as well as any other features you’d like included!

Also, a quick note that I forgot to mention about Stripe in my last post is that you can accept payments from any country (Visa, MasterCard, American Express, Discover, JCB, and Diners Club cards) and customers can use pretty much any currency, but you currently have to be based in the US to receive payments. Sounds like they are working to expand to other countries though. Check out their FAQ for more information.

2011
12.29

How do you usually process credit cards in your web applications? There are obviously lots of options available and each has pros and cons. One that I am really starting to like though is Stripe. It has great client libraries, makes PCI compliance really easy and is incredibly easy to use! So, I decided to build a Grails plugin for Stripe! The purpose of this post is to introduce people to the plugin and hopefully get feedback on it before releasing a “1.0 Final” version. I am NOT affiliated with Stripe Inc, I just like it, ha! Let’s dive in!

First, you will need a sample Grails 2.0 application. You could certainly use Grails 1.3.7 too as there’s nothing limiting the plugin to 2.0, but it does require the resources plugin and I just figure most new Grails apps will be 2.0.


grails create-app stripesample
cd stripesample
grails install-plugin stripe
grails create-controller checkout

We will need to set two configuration items in Config.groovy. Before we can add these though, we need to register for a Stripe account. So, head on over to Stripe and create your account. Once you’re logged in, click on the top-right link for Your Account and then Account Settings. This will pop open a box where you can find your API Keys. Stripe provides each account with separate publishable and secret keys for testing and live. We only care about the testing ones for now. Let’s add these two values to our sample application’s config file:

stripesample/grails-app/Config.groovy

grails.plugins.stripe.secretKey = 'YOUR_TEST_SECRET_KEY'
grails.plugins.stripe.publishableKey = 'YOUR_TEST_PUBLISHABLE_KEY'

You will obviously want to put these config values in the appropriate environment in Config.groovy. The plugin takes care of setting the secret key for you in the Stripe abstract class and the publishable key will be set from our JavaScript which we’ll cover in a bit.

Next we need to include the JavaScript library provided by Stripe. The plugin exposes this library as a standard resource module called stripe. So, you need to include this in your resource modules declaration. Make sure you use modules (plural) if you have more than one as opposed to module (singular).


<r:require modules="application, stripe"/>

or

<r:require module="stripe"/>

The way Stripe works is that it uses JavaScript to capture the credit card details and creates a token. So, the credit card details never actually hit the server which makes it really easy to be PCI compliant. The JavaScript then creates a hidden field on the form with the token as the value and submits the form to the server. Once on the server, we will use Groovy to capture the amount from the form, the token and create a Stripe Charge. Piece of cake!

Create a new file called index.gsp in stripesample/grails-app/views/checkout and put the following for the contents of the file:

Next we need to modify the CheckoutController we created. Put the following for the contents of this file:

And finally, we need to create a simple confirmation.gsp in stripesample/grails-app/views/checkout and put the following for the contents of the file:

This is obviously a really simple example and can be improved greatly with styling, validation, flash message, etc, but I did this on purpose just to keep it really simple. A couple things to notice in the sample code:

  1. The JavaScript is pulling in your publishable key from Config.groovy
  2. The JavaScript then takes the credit-card details and creates a token and inserts this into a hidden-field on the form
  3. The server never sees the credit-card details, only the token created by the Stripe JavaScript library and the amount to charge

Let’s try it out! Here are some sample values that will work for testing:

  • Credit Card Number: 4242424242424242
  • CVC: 123
  • Expiration Month: 12
  • Expiration Year: 2015

You can use whatever you want for the amount. Enter it as you normally would in dollars like 12.99 for example. The controller converts this to an integer of cents since Stripe deals in cents. If goes well, you should see the confirmation page with the success message! If something goes wrong and you receive the error message, you can comment out the try/catch block around the Charge.create(chargeParams) to see the actual error message from the Stripe API. Once you have successfully submitted the form and received the confirmation message, go to your Stripe account and click on Payments to verify that it shows up!

This post is just barely touching the surface of the Stripe capabilities! We did a one-time charge here, but you can do all sorts of stuff with the Stripe API with Groovy like subscriptions / plans for recurring payments. You can also do standard stuff like issue refunds or coupons. Take a look at the Java API documentation for more details.

Well that concludes my walk-through of using Stripe for processing credit cards in a Grails application. I hope you found this post interesting and consider trying out my plugin! Here are links to the source for the plugin and the plugin portal page.

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.

Switch to our mobile site