Support Questions

Find answers, ask questions, and share your expertise

Groovy ExcuteScript example ?

avatar
Rising Star

Hello forum,

I got the below example from funnifi blog, thanks to Matt 🙂

I have 2 questions on this ?

1- Groovy supposed to be Java like language, classes and methods... but I can't see this in the below example ? no class or method declaration ?

2- If I want to add conditions to the code and modify the output based on this.

e.g.

if field 3 (column C) starts with 3300, replace 33 with 22

if field 3 (column C) starts with 0, replace this 0 with 00212

how to achieve this ?

Input file:

a1|b1|c1|d1
a2|b2|c2|d2
a3|b3|c3|d3

Desired output:

b1 c1
b2 c2
b3 c3

script:

import java.nio.charset.StandardCharsets

def flowFile = session.get()
if(!flowFile) return

flowFile = session.write(flowFile, {inputStream, outputStream ->
   inputStream.eachLine { line ->
   a = line.tokenize('|')
   outputStream.write("${a[1]} ${a[2]}\n".toString().getBytes(StandardCharsets.UTF_8))
   }
} as StreamCallback)

session.transfer(flowFile, REL_SUCCESS)
1 ACCEPTED SOLUTION

avatar
Master Mentor

Heres an example of groovy class in ExecuteScript processor, treat it like Java and use Matt's nifi-script-tester utility to debug your code

https://github.com/dbist/workshops/blob/master/nifi/templates/zabbix/ZabbixSender.groovy#L36-L56

View solution in original post

3 REPLIES 3

avatar
Master Mentor

Heres an example of groovy class in ExecuteScript processor, treat it like Java and use Matt's nifi-script-tester utility to debug your code

https://github.com/dbist/workshops/blob/master/nifi/templates/zabbix/ZabbixSender.groovy#L36-L56

avatar
Rising Star

thank you 🙂

avatar
Master Guru

To follow up on your first question above, Groovy has many features and supports multiple paradigms such as OO (like Java), functional programming, etc. Also it can be used as a scripting language, which is why you don't often see explicitly-defined classes and methods in the example scripts (both in @Artem Ervits answer and the examples on my blog).

For ExecuteScript, the Script Body is treated like a script, so it can be evaluated without needing to define a top-level class. Under the hood, Groovy wraps the script in a Script object (such that it obeys the JVM rules).

For your second question, you can add additional logic inside the inputStream.eachLine closure to do any transformations. So instead of just writing out a[1] a[2] after you've tokenized the input stream, you can do additional things such as:

if(a[2].startsWith('3300')) a[2] = a[2].replaceFirst('33','22')
if(a[2].startsWith('0')) a[2] = a[2].replaceFirst('0','00212')

Then you can output the space-separated columns.