Gradle Goodness: Running Groovy Scripts Using Like From Command Line
In a previous post we have seen how to execute a Groovy script in our source directories. But what if we want to use the Groovy command line to execute a Groovy script? Suppose we want to evaluate a small Groovy script expressed by a String value, that we normally would invoke like $ groovy -e "println 'Hello Groovy!'"
. Or we want to use the command line option -l
to start Groovy in listening mode with a script to handle requests. We can achieve this by creating a task with type JavaExec
or by using the Gradle javaexec
method. We must set the Java main class to groovy.ui.Main
which is the class that is used for running the Groovy command line.
In the following sample build file we create a new task runGroovyScript
of type JavaExec
. We also create a new dependency configuration groovyScript
so we can use a separate class path for running our Groovy scripts.
// File: build.gradle
repositories {
jcenter()
}
// Add new configuration for
// dependencies needed to run
// Groovy command line scripts.
configurations {
groovyScript
}
dependencies {
// Set Groovy dependency so
// groovy.ui.GroovyMain can be found.
groovyScript localGroovy()
// Or be specific for a version:
//groovyScript "org.codehaus.groovy:groovy-all:2.4.5"
}
// New task to run Groovy command line
// with arguments.
task runGroovyScript(type: JavaExec) {
// Set class path used for running
// Groovy command line.
classpath = configurations.groovyScript
// Main class that runs the Groovy
// command line.
main = 'groovy.ui.GroovyMain'
// Pass command line arguments.
args '-e', "println 'Hello Gradle!'"
}
We can run the task runGroovyScript
and we see the output of our small Groovy script println 'Hello Gradle!'
:
$ gradle runGroovyScript
:runGroovyScript
Hello Gradle!
BUILD SUCCESSFUL
Total time: 1.265 secs
$
Let's write another task where we use the simple HTTP server from the Groovy examples to start a HTTP server with Gradle. This can be useful if we have a project with static HTML files and want to serve them via a web server:
// File: build.gradle
repositories {
jcenter()
}
configurations {
groovyScript
}
dependencies {
groovyScript localGroovy()
}
task runHttpServer(type: JavaExec) {
classpath = configurations.groovyScript
main = 'groovy.ui.GroovyMain'
// Start Groovy in listening mode on
// port 8001.
args '-l', '8001'
// Run simple HTTP server.
args '-e', '''
// init variable is true before
// the first client request, so
// the following code is executed once.
if (init) {
headers = [:]
binaryTypes = ["gif","jpg","png"]
mimeTypes = [
"css" : "text/css",
"gif" : "image/gif",
"htm" : "text/html",
"html": "text/html",
"jpg" : "image/jpeg",
"png" : "image/png"
]
baseDir = System.properties['baseDir'] ?: '.'
}
// parse the request
if (line.toLowerCase().startsWith("get")) {
content = line.tokenize()[1]
} else {
def h = line.tokenize(":")
headers[h[0]] = h[1]
}
// all done, now process request
if (line.size() == 0) {
processRequest()
return "success"
}
def processRequest() {
if (content.indexOf("..") < 0) { //simplistic security
// simple file browser rooted from current dir
def file = new File(new File(baseDir), content)
if (file.isDirectory()) {
printDirectoryListing(file)
} else {
extension = content.substring(content.lastIndexOf(".") + 1)
printHeaders(mimeTypes.get(extension,"text/plain"))
if (binaryTypes.contains(extension)) {
socket.outputStream.write(file.readBytes())
} else {
println(file.text)
}
}
}
}
def printDirectoryListing(dir) {
printHeaders("text/html")
for (file in dir.list().toList().sort()) {
// special case for root document
if ("/" == content) {
content = ""
}
println "<li><a href='${content}/${file}'>${file}</a></li>"
}
}
def printHeaders(mimeType) {
// See original blog post for full example.
// The blog we use here doesn't allow to
// use Http header.
println "${'http'.toUpperCase()}/1.0 200 OK"
println "Content-Type: ${mimeType}"
println ""
}
'''
// Script is configurable via Java
// system properties. Here we set
// the property baseDir as the base
// directory for serving static files.
systemProperty 'baseDir', 'src/main/resources'
}
We can run the task runHttpServer
from the command line and open the page http://localhost:8001/index.html in our web browser. If there is a file index.html
in the directory src/main/resources
it is shown in the browser.
$ gradle runGroovyScript
:runHttpServer
groovy is listening on port 8001
> Building 0% > :runHttpServer
Written with Gradle 2.11.