Red Hat Israel
רד הט ישראל להתחיל

Groovying with Java

Tomer Figenblat - Senior Software Engineer
a groovy image

Combining Groovy scripts in our Java-based code, is easy with Maven.

You can check out the code for this tutorial in Github.

Let's say we need to produce a text message for sending to customers registering to some sort of call queue for informing them that we got their registration request.
The message should include the customer name, queue number, and an informational greeting of some sort.

We have a couple of ways to accomplish that in Java.

First, we can use a basic method that takes the name and queue number as arguments:

private static String createMessage(final String name, final int queueNum) {
return String.format(
"Hello %s, you're number %d, please wait patiently, here is some info:\n" +
"Anim incididunt deserunt ex ad do aliquip.\n" +
"Ipsum voluptate laboris eiusmod sint ea do.", name, queueNum);
}

public String getMessage(final String name, final int queueNum) {
return createMessage(name, queueNum);
}

Let's try this as a BiFunction:

private static final BiFunction<String, Integer, String> createMessage =
(name, queueNum) -> String.format(
"Hello %s, you're number %d, please wait patiently, here is some info:\n" +
"Anim incididunt deserunt ex ad do aliquip.\n" +
"Ipsum voluptate laboris eiusmod sint ea do.", name, queueNum);

public String getMessage(final String name, final int queueNum) {
return createMessage.apply(name, queueNum);
}

For the above implementations, adding an argument, i.e. an eta, will complicate our code.

So let's do function currying, it will make it easier to add arguments later on,
and... well... it's fun invoking currying functions, am I right? 😁

private static final Function<String, Function<Integer, String>> createMessage =
name -> queueNum -> String.format(
"Hello %s, you're number %d, please wait patiently, here is some info:\n" +
"Anim incididunt deserunt ex ad do aliquip.\n" +
"Ipsum voluptate laboris eiusmod sint ea do.", name, queueNum);

public String getMessage(final String name, final int queueNum) {
return createMessage.apply(name).apply(queueNum);
}

Now, Let's give Groovy a try.
We'll create Groovy Script called create_message.groovy:

def name = bindName
def queueNum = bindQueueNum

"""Hello ${name}, you're number ${queueNum}, please wait patiently, here is some info:
Anim incididunt deserunt ex ad do aliquip.
Ipsum voluptate laboris eiusmod sint ea do."""

Now let's invoke the script from our Java code:

public String getMessage(final String name, final int queueNum) {
try {
var shell = new GroovyShell();
var scriptFile = new File(shell.getClassLoader().getResource("scripts/create_message.groovy").getFile());

var script = shell.parse(scriptFile);

var binding = new Binding();
binding.setProperty("bindName", name);
binding.setProperty("bindQueueNum", queueNum);

script.setBinding(binding);

return script.run().toString();
} catch (IOException exc) {
return exc.getMessage();
}
}

Now, if we want to add an eta, it's as simple as editing the text and binding another property. 😌

To get our our script into our class path with Maven, let's say this is our project layout:

- project
- src
- main
- *.java
- scripts
- create_message.groovy
- test
- *Test.java

First, we need to include the groovy dependency.
This will give access to Groovy's API, i.e. the GroovyShell and Binding classes.

<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>3.0.5</version>
</dependency>
</dependencies>

We'll add the following to our build section in our pom.xml,
This will add everything from our src/scripts to our project.

<build>
<resources>
<resource>
<directory>src/scripts</directory>
<targetPath>scripts</targetPath>
</resource>
</resources>
</build>

That's it, have fun and stay groovy!

You can check out the code for this tutorial in Github.

👋 See you in the next tutorial 👋

Red Hat Israel logo LinkedIn Youtube Facebook Twitter GitHub

המוצרים שלנו

צרו קשר

רד האט

רד האט היא החברה המובילה בעולם לפתרונות תוכנה מבוססי קוד פתוח לארגוני Enterprise. רד האט מבוססת על כוחה של קהילת הקוד הפתוח בפיתוח ואספקת טכנולוגיות Linux, Cloud, Container, ו-Kubernetes. אנחנו מסייעים ללקוחות לשלב בין יישומי IT חדשים וקיימים, לפתח יישומים רב-ענניים (multi-cloud), לבצע סטנדרטיזציה של מערכת ההפעלה, יחד עם אוטומציה, אבטחה וניהול של סביבות מורכבות.