Tuesday, October 18, 2011

Groovy Goodness: Run Remote Scripts via URL

Since Groovy 1.8.3 we can run remote Groovy scripts. We can use an URL to refer to the Groovy script that we want to execute. This can be very useful to build a library of Groovy scripts and publish them on a web server or a code repository like Github. Then we can run those scripts by referring the scripts by URL.

// File:
// http://www.mrhaki.com/samples/remotesample.groovy

printMessage 'Remote Groovy script @ http://www.mrhaki.com/samples/remotesample.groovy'

['Groovy', 'rocks'].each {
    print "${it.toUpperCase()} "
println '!'

def printMessage(message) {
    def LINE_LENGTH = message.size() + 4
    println '*' * LINE_LENGTH
    println "* $message *"
    println '*' * LINE_LENGTH

On a command line we run $ groovy http://www.mrhaki.com/samples/remotesample.groovy and we get the following output:

$ groovy http://www.mrhaki.com/samples/remotesample.groovy
* Remote Groovy script @ http://www.mrhaki.com/samples/remotesample.groovy *


Anonymous said...

How does the groovy command decide whether to interpret the script-name argument as a URI or a file pathname?

In particular, if you give "groovy d%69r/x.groovy", does it try to execute the file at dir/x.groovy or the file at d%69r/x.groovy?

Does it interpret the script name as a URI only if it's an absolute URI? Or does it check something else to decide which interpretation
to use?

mrhaki said...

@Anonymous: If the script file argument starts with http, https or file: than a URL object is created to get the script file contents. Otherwise a file pathname is assumed to get the contents of the script file.

Post a Comment