Using Groovy on the AWS Lambda Java8 Runtime

Posted in Code on September 11th, 2015 by ataylor284 – Be the first to comment

AWS Lambda is a service for running code in the cloud that manages its resources automatically. Since it provides a full Java 8 runtime, it is possible to use groovy to write your Lambda services.

When you deploy a Lambda service, you need to bundle up all your resources into a single jar file. To run groovy, you simply need to include the groovy runtime in your jar.

Gradle makes this easy. First declare groovy as a compile dependency:

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.4.4'

Next, update the jar target to include all the runtime dependencies in the jar:

jar {
    dependsOn configurations.runtime
    from {
        configurations.runtime.collect {
            it.isDirectory() ? it : zipTree(it)

This bundles all the “compile” and “runtime” dependencies into one big “fat jar”.

For a full working example, check out groovy-aws-lambda on github.

Setting Headers on URL Requests with Groovy

Posted in Code on February 6th, 2014 by ataylor284 – 2 Comments

The Java URL class can be used to send quick and dirty HTTP requests. In Groovy, it’s especially convenient to quickly get content from the web. This one-liner will fetch the page’s contents:

def webpage = "".toURL().text

Although it’s not well documented, Groovy also provides a convenient way to set headers on the request:

def json = "".toURL().
    getText(requestProperties: [Accept: 'application/json'])

See also: Url.getText(Map parameters)

Logging HttpBuilder traffic

Posted in Code on October 18th, 2013 by ataylor284 – Be the first to comment

Groovy and HttpBuilder are a nice way to write quick scripts to exercise web services. It’s especially useful when it’s just a bit too complex for something like curl. Unfortunately, there’s no quick way to trace all the I/O as with curl’s –trace, but turning on logging isn’t too difficult.

HttpBuilder uses HttpClient, which does some logging with Apache’s commons-logging. Without any additional libraries or configuration, it will fall back on Java’s java.util.logging package. Java expects it’s logging configuration in a properties file. Here’s a minimal config:


Launch groovy with the right system property, and all the output will be logged.

groovy \

Creating a Groovy ConfigObject from a Closure

Posted in Code on January 22nd, 2013 by ataylor284 – 5 Comments

The Groovy ConfigObject and ConfigSlurper are very nice for replacing properties and XML configuration files with Groovy. Surprisingly though, there’s no obvious way to get a ConfigObject directly from a closure. The interface requires either the URL or filename of a script file, or a Script object.

Fortunately, there’s an easy way wrap a closure to make it work like a Script:

class ClosureScript extends Script {
    Closure closure
    def run() {
        closure.resolveStrategy = Closure.DELEGATE_FIRST
        closure.delegate = this

This makes it trivial to include a configuration configuration directly inside a script and treat it just like an external script.

def config = {
  environments {
    development {
      host = 'localhost'
      port = 8080
def env = 'development'
def settings = new ConfigSlurper(env).
    parse(new ClosureScript(closure: config))
println "host is $, port is $settings.port"

Downloading a Server’s HTTPS Certificate with Groovy

Posted in Code on August 2nd, 2012 by ataylor284 – 1 Comment

If you ever need to access a web service with HTTPS as a client in Java or groovy, and the service uses a self-signed certificate, you might need to import the SSL certificate into your local keystore.

To import the certificate, first you need to get it from the remote web server. Here’s a convenient little groovy script that downloads the certificate as a X509Certificate.


if (args.size() != 2) {
    println "usage: getCert host port"
def (host, port) = args
def cert
def trustManager = [
    checkClientTrusted: { chain, authType ->  },
    checkServerTrusted: { chain, authType -> cert = chain[0] },
    getAcceptedIssuers: { null }
] as X509TrustManager

def context = SSLContext.getInstance("TLS")
context.init(null, [trustManager] as TrustManager[], null)
context.socketFactory.createSocket(host, port as int).with {
println "-----BEGIN CERTIFICATE-----"
println cert.encoded.encodeBase64(true)
println "-----END CERTIFICATE-----"

This program prints out the certificate in a format that can be fed to keytool like so:

# get the certificate from the remote server
groovy getCert testserver 443 > certificate.txt
# print out the certificate details in a readable format
keytool -printcert -file certificate.txt
# import the certificate into the local keystore
keytool -import -file certificate.txt -alias testserver -keystore $JAVA_HOME/jre/lib/security/cacerts

Spring Beans from the Grails console

Posted in Code on May 8th, 2012 by ataylor284 – Comments Off

For Spring newbies, the objects Spring automatically instantiates and injects can be quite opaque. The grails console is great tool for understanding all the underlying Spring infrastructure.

This little snippet will list all the objects currently managed by Spring:


To access a bean by name:


Or to get a list of services, taking advantage of the grails naming convention:

serviceNames = ctx.getBeanNamesForType(Object).findAll{it.endsWith('Service')}.sort().join('\n')

One of the more useful objects Spring can provide is the dataSource. You can use this for doing ad-hoc SQL manipulation without going through the Hibernate layer.

import groovy.sql.Sql
def dataSource = ctx.getBean('dataSource')
new Sql(dataSource).eachRow('select * from table') { row ->
    println row

Simple Servlets in Groovy

Posted in Code on February 29th, 2012 by ataylor284 – 12 Comments

A feature I miss in groovy is a simple way to create a self-contained web server without a web container like Tomcat. Python, in particular, has a nice solution for this with its HTTPServer class. It’s not something to write a full application with, but it’s an extremely convenient tool to have available.

The best solution I’ve found is Jetty, the embedded Java web server. It has a nice simple interface and runs any Servlet right out of your script:

@Grab(group='org.mortbay.jetty', module='jetty-embedded', version='6.1.26')
import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.*

def runWithJetty(servlet, port) {
   def jetty = new Server(port)
   def context = new Context(jetty, '/', Context.SESSIONS)
   context.addServlet(new ServletHolder(servlet), '/*')

Groovy has groovlets and GroovyServlet, a nice little wrapper for writing Servlets. However, it requires you to structure your project in a specific way: each Servlet in a separate file, mapped to URI paths by file name.

By hooking up ServletCategory and ServletBinding to a closure, it’s possible to get the nice features of groovlets without the GroovyServlet limitations:

@Grab(group='org.mortbay.jetty', module='jetty-embedded', version='6.1.26')
import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.*
import groovy.servlet.*
import javax.servlet.http.*
import javax.servlet.ServletConfig

class SimpleGroovyServlet extends HttpServlet {
    def requestHandler
    def context
    void init(ServletConfig config) {
        context = config.servletContext
    void service(HttpServletRequest request, HttpServletResponse response) {
        requestHandler.binding = new ServletBinding(request, response, context)
        use (ServletCategory) {
    static void run(int port, Closure requestHandler) {
        def servlet = new SimpleGroovyServlet(requestHandler: requestHandler)
        def jetty = new Server(port)
        def context = new Context(jetty, '/', Context.SESSIONS)
        context.addServlet(new ServletHolder(servlet), '/*')

Combined with the above, a simple self-contained web server becomes as clean and concise as groovy should be: { ->
    response.contentType = 'text/plain'
    println "hello world!"
    println "my path is ${request.pathInfo}"
    println "my params are $params"

Guess the Content-type from Filename

Posted in Code on January 17th, 2012 by ataylor284 – Be the first to comment

Java has a helpful little function for guessing the content-type based on the file name:


You can check out — or customize — the mappings which are stored in $JRE_HOME/lib/

So if you’re serving up a file and you’re not quite sure what content-type to use, let Java take a guess.

Encrypting a Database Column in Grails

Posted in Code on December 14th, 2011 by ataylor284 – Be the first to comment

Grails and hibernate user types make it easy to encrypt tables on a column by column basis.

Note that this approach has some limitations. Most importantly, you won’t be able to make queries based on the encrypted field, since they’ll try to match against the encrypted text instead of the plaintext.

The grails mapping DSL allows the user type to be specified easily:

    import ca.redtoad.crypto.hibernate.EncryptedString

        static mapping = {
            ccNumber type: EncryptedString

Here’s the implementation of the user type. It stores the encrypted value as a JSON map containing the base64 encoded encrypted value and the salt. A text-based JSON representation is purely for convenience — it could easily be stored in binary form in a BLOB column to save space and parsing overhead.

package ca.redtoad.crypto.hibernate

import java.sql.*
import org.codehaus.groovy.grails.commons.ApplicationHolder
import org.hibernate.*
import org.hibernate.usertype.UserType
import grails.converters.JSON
import javax.crypto.*
import javax.crypto.spec.*

class EncryptedString implements UserType {

    int[] sqlTypes() { [Types.VARCHAR] as int[] }
    Class returnedClass() { String }
    boolean equals(x, y) { x == y }
    int hashCode(x) { x.hashCode() }
    Object deepCopy(value) { value }
    boolean isMutable() { false }
    Serializable disassemble(value) { value }
    def assemble(Serializable cached, owner) { cached }
    def replace(original, target, owner) { original }

    Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
        String str = resultSet.getString(names[0])
        str ? decrypt(str) : null

    void nullSafeSet(PreparedStatement statement, Object value, int index) {
        statement.setString(index, value ? encrypt(value) : null)
    private String encrypt(String plaintext) {
        String salt = 'Salt!'
        String key = "myKey"
        Cipher c = Cipher.getInstance('AES')
        byte[] keyBytes = MessageDigest.getInstance('SHA-1').digest("$salt$key".getBytes())[0..<16]
        c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, 'AES'))
        [data: c.doFinal(plaintext.bytes).encodeBase64() as String, salt: salt] as JSON

    private String decrypt(String ciphertext) {
        def json = JSON.parse(ciphertext)
        Cipher c = Cipher.getInstance('AES')
        String key = "myKey"
        byte[] keyBytes = MessageDigest.getInstance('SHA-1').digest("${json.salt}${key}".getBytes())[0..<16]
        c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, 'AES'))
        new String(c.doFinal(json['data'].decodeBase64()))

The H2 Database Console in Grails 2

Posted in Code on November 15th, 2011 by ataylor284 – 1 Comment

The H2 Database Engine replaces HSQLDB as the default, embedded database engine in Grails 2.0. One of the great features it adds is a web-based console for browsing tables, checking the schema, executing SQL queries, and all the other stuff you’d use a database client for.

This was possible in older versions of grails but it comes ready to go out of the box in Grails 2. It’s mapped to http://localhost:8080/<app-name>/dbconsole.

Let’s create a quick grails app to see it in action:

$ grails create-app test-app
| Created Eclipse project files.
| Created Grails Application at ~/dev/test-app
$ cd test-app
$ grails
| Enter a script name to run. Use TAB for completion:
grails> run-app
| Server running. Browse to http://localhost:8080/test-app
| Application loaded in interactive mode. Type 'exit' to shutdown.
| Enter a script name to run. Use TAB for completion:

At this point, browse to http://localhost:8080/test-app/dbconsole. The default login parameters should match the defaults in grails-app/conf/DataSource.groovy, so pressing Connect should log us into the development database.

H2 Database Console Login Window

H2 Database Console Login Window

grails> create-domain-class test.Book
| Created file grails-app/domain/test/Book.groovy

Book.groovy will be an empty domain class, so open it up add a title property. Then hit refresh in the console, and now we see a BOOK table in the right sidebar. Let’s create a book instance with the grails shell:

grails> shell
| Packaging Grails application.....
Groovy Shell (1.8.3, JVM: 1.6.0_29)
Type 'help' or '\h' for help.
groovy:000> new test.Book(title: 'Grails in Action').save(failOnError: true)
===> test.Book : 1
groovy:000> exit

Now if we enter SELECT * FROM BOOK in the database console, our book will show up.

H2 Database Console

H2 Database Console