Using Groovy as a scripting language
Asked Answered
P

7

12

I prefer to use scripting languages for short tasks, anything such as a really simple http bot, bulk importing/exporting data to/from somewhere, etc etc... Basic throw-away scripts and simple stuff. The point being, that a scripting language is just an efficient tool to write quick programs with. As for my understanding of Groovy at this point...

If you were to program in Groovy, and you wan't to write a quick script, wouldn't you be forced to going back to regular java syntax (and we know how that can be convoluted compared to a scripting language) in order to do anything more complicated? For example, if I want to do some http scripting, wouldn't I just be right back at using java syntax to invoke Commons HttpClient? To me, the point of a scripting language is for quickly typed and less forced constructs. And here is another thing, it doesn't seem that there is any incentive for groovy based libraries to be developed when there are already so many good java one's out there, thus making groovy appear to be a Java dependent language with minor scripting features.

So right now I am wondering if I could switch to Groovy as a scripting language or continue to use a more common scripting language such as Perl, Python or Ruby.

Poundage answered 15/4, 2010 at 13:46 Comment(0)
W
15

@Zombies, let me show you a quick example from a script I wrote recently:

def fetch(build, toFile) {
    new FTPClient().with {
        connect ftpServer
        enterLocalPassiveMode()
        login ftpUser, ftpPassword
        changeWorkingDirectory "/var/staging/revision-${build}"
        fileType = FTPClient.BINARY_FILE_TYPE
        toFile.withOutputStream { ostream -> 
            retrieveFile "build-${build}.zip", ostream 
        }
        disconnect()
    }
}

It uses commons-net API, but I think you would agree that it has a much clearer syntax than comparable Java program. So I don't think using the Java APIs defeats the purpose of having a scripting language. Furthermore, it helps you leverage your existing knowledge of the Java APIs, so is a very pragmatic approach.

Waterhouse answered 15/4, 2010 at 17:33 Comment(0)
T
6

One goal of Groovy is to have transparent interoperability with Java. Groovy is by design "a Java dependent language with scripting features". However, I don't think that these features are minor - Groovy has many features that are not found in static programming languages (such as Java).

To summarize: If you don't care at all about Java, then use a more general-purpose scripting language, such as Python or Perl. If you want to use the Java code-base in a script-ish way, Groovy is a good option.

Triform answered 15/4, 2010 at 13:53 Comment(2)
Actually I use Java a lot and I can incorporate a scripting language such as Groovy into the company where I work too. My concern is that if I have to use java JAR's, I seem to be defeating the purpose of having a scripting language. So yeah, I know groovy has great scripting features, but my question is wouldn't I have to use rigid java syntax in order to use third party JAR's such as Common's HttpClient? Also, there wouldn't seem to be much support for say a groovy based http client. I much rather use Mechanize on Perl than HttpCommons on Groovy if I truely am scripting.Poundage
Excellent question and excellent answer. I am a Java programmer and I strongly recommend any other primarily-Java programmer to learn and use Groovy, due to its very low learning curve, and its easy (almost trivial) interoperability with Java and Java libraries. But as much as I like Groovy, by contrast, if someone is not a Java programmer, I wouldn't see much use in learning Groovy. Good and bad, Groovy is tied to Java, and if you're not a Java programmer you'd probably find some other scripting language more useful.Transmitter
G
5

Groovy can be quite handy for scripting. Recently I needed a script to fetch Maven dependencies into a lib directory and ended up with a groovy script. This snippet parses a pom and gives you a list of jars. Pretty sweet for XML parsing!

#!/usr/bin/env groovy
def pom = new XmlSlurper().parse('pom.xml')
def repo = "${System.env.HOME}/.m2/repository"

pom.dependencies.dependency.each { dep ->
    def jarName = "${dep.artifactId}-${dep.version}.jar"
    def groupPath = dep.groupId.text().replaceAll('\\.', '/')
    def jarPath = "${repo}/${groupPath}/${dep.artifactId}/${dep.version}"
    println "$jarPath/$jarName"
}
Gaultiero answered 15/4, 2010 at 21:7 Comment(0)
W
4

For example, if I want to do some http scripting, wouldn't I just be right back at using java syntax to invoke Commons HttpClient?

You would be "right back at using Commons HttpClient", but you would invoke it using Groovy syntax, not Java syntax. Groovy syntax is a lot more compact than Java syntax and therefore better suited for scripting. In other words, using Java libraries in Groovy takes a lot less code than using Java libraries in Java.

it doesn't seem that there is any incentive for groovy based libraries to be developed when there are already so many good java one's out there

Rather than developing an entirely new library, a Groovy library author will often provide a "Groovier" API to an existing Java library. Examples include the Hibernate builder provided by Grails, and the HTTP Builder (which delegates to Commons HttpClient).

These Groovy APIs provide a more compact and idiomatic alternative to using the Java API directly.

Waltz answered 15/4, 2010 at 15:43 Comment(0)
B
4

Groovy "out of the box" replaces a large number of common classes with groovier versions or language constructs, including classes for XML, HTTP requests, accessing SQL databases and regular expressions. For most scripting tasks, you won't have to use Java libraries at all (although you'll still have that option). But if your script uses bare Java libraries, you'll be much farther ahead with Groovy over straight Java. Where Groovy shines is in the "glue" code, such as setting up data structures and file I/O.

The map and list allow you to create Java compatible Lists and Maps; regular Java objects that work with Java classes. Groovy often turns a multi-line Java method invokation with variable declarations and initalization into a one-liner.

Consider this short snippet to load an entire file into a String:

def fileContents = new File(filename).text

versus

String fileContents = "";
try {
    BufferedReader reader = new BufferedReader(new FileInputStream(filename));
    String line = null;
    while ((line = reader.readLine()) != null) {
        text = text + line + "\n";
    }
} catch (IOException e) {
    e.printStackTrace();
}

Exception handling is often not an important consideration in scripts and it can be conveniently ignored.

Groovy's main strength as a scripting language is accessing the enormous library of Java code that's out there directly and conveniently. If that's not your need, groovy still provides a scripting environment about as rich as other languages such as perl, python or ruby.

Birth answered 15/4, 2010 at 17:35 Comment(0)
R
2

Groovy rocks, once you get a hang of the very tight syntax, you start to use it for a lot of things you've just done "the slow way".

The other day I was in a discussion which somehow got to wondering how many chars we have in a GUID in one of our systems. Rather than just count the digits, it was easier to just do this:

def str = '92228498-6A2F-DBA2-7A2C-F54B9E607E3A'
int num = 0
str.each {
    num++
}
println num

Whack that in a local or shared scripts directory and it'll be there for the future.

Ripplet answered 21/6, 2011 at 7:18 Comment(0)
M
0

Only use:

error('bla bla bla bla')

Exemple in script Jenkins:

// define vars
def env.TYPE_GESTAO = "VASCO"
def _MSSQL_FILE = "ALL_CHK.sql"
def _MSSQL_USER = "master"


// Start pipeline
pipeline {
    agent any

    stages {
        stage('Checking the envs with vars') {
            steps {
                script {
                    // Print Vars
                    print "_MSSQL_FILE -- ${_MSSQL_FILE}"
                    print "_MSSQL_USER -- ${_MSSQL_USER}"

                    // if
                    if (env.TYPE_GESTA.toUpperCase() == 'FLUMINENSE') {
                        _MSSQL_FILE = "SOMEFILE.sql"
                        _MSSQL_USER = "someuser"

                    // else if
                    } else if (env.TYPE_GESTA.toUpperCase() == 'FLAMENGO') {
                        _MSSQL_FILE = "SOMEFILE.sql"
                        _MSSQL_USER = "someuser"

                    } else {
                        print "---------"
                        error('RUN_MODE is not set. Set this var in project Jenkins.')
                    }

                    // Print Vars
                    print "-----------------------------"
                    print "_MSSQL_FILE -- ${_MSSQL_FILE}"
                    print "_MSSQL_USER -- ${_MSSQL_USER}"
                }
            }
        }


        stage('Checking something else STAGE') {
            steps {
                script {
                    print "END OF SCRIPT..."
                }
            }
        }
    }
}

Macaw answered 1/3, 2023 at 20:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.