DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Prompt Engineering: Unlocking the Power of Generative AI Models
  • Execution Type Models in Node.js
  • Zero Trust Network for Microservices With Istio
  • Revolutionize JSON Parsing in Java With Manifold

Trending

  • Prompt Engineering: Unlocking the Power of Generative AI Models
  • Execution Type Models in Node.js
  • Zero Trust Network for Microservices With Istio
  • Revolutionize JSON Parsing in Java With Manifold
  1. DZone
  2. Coding
  3. Languages
  4. Gradle Goodness: Running Groovy Scripts Using Groovy Command Line

Gradle Goodness: Running Groovy Scripts Using Groovy Command Line

In a previous post, we showed 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? Read on and see how it's done.

Hubert Klein Ikkink user avatar by
Hubert Klein Ikkink
·
Feb. 18, 16 · Tutorial
Like (1)
Save
Tweet
Share
14.69K Views

Join the DZone community and get the full member experience.

Join For Free

In a previous post, we showed 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 $ 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 that 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 an 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")
    println "<html><head></head><body>"
    for (file in dir.list().toList().sort()) {
        // special case for root document
        if ("/" == content) {
            content = ""
        }
        println "<li><a href='${content}/${file}'>${file}</a></li>"
    }
    println "</body></html>"
}

def printHeaders(mimeType) {
    println "HTTP/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.

Groovy (programming language) Command (computing) Gradle

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Prompt Engineering: Unlocking the Power of Generative AI Models
  • Execution Type Models in Node.js
  • Zero Trust Network for Microservices With Istio
  • Revolutionize JSON Parsing in Java With Manifold

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: