Thursday, June 13, 2013

Passing a Variable out of a tGroovy with Talend Open Studio


It's possible to pass a variable out of a tGroovy, but you'll need to use Java. Rather than binding and manipulating a a variable of the form "context.MYPARAM" or even globalMap, you'll need to create a Map for yourself in a tJava and pass _THAT_ as your parameter.

This is because of Java's call-by-value semantics.  In previous examples on this blog, the Groovy scripts received variables (objects) through parameter passing.  These simple objects couldn't be changed in the Groovy code defined in the component.  However, if a complex object (like java.util.Map) is used, the individual properties of the Map can be changed.

For example, in a tJava -> tGroovy -> tJava job.

Job Calling the tGroovy Component

1. Declare a global variable in the first tJava that references a new Map object

java.util.Map groovyParams = new java.util.HashMap();

groovyParams.put("param1", "p1 value");

globalMap.put("groovyParams", groovyParams);

System.out.println("[1st tJava] params1=" + ((Map)globalMap.get("groovyParams")).get("param1"));


Setting up a Java Map to be Used Throughout the Job

2. Add and bind a Groovy parameter to this variable in the component view of the tGroovy

"groovyParams" / globalMap.get("groovyParams")

3. In the code for the tGroovy component, set the variable

println("[tGroovy] param1:" + groovyParams.param1)
groovyParams.param1 = "value set in groovy"
println("[tGroovy] param1 after assign: " + groovyParams.param1)


tGroovy Binding to Global Variable and Setting a Parameter

4. Finally, verify the output in the second tJava. Access the Map and print the results

java.util.Map groovyParams = (java.util.Map)globalMap.get("groovyParams");
System.out.println("[2nd tJava] param1=" + groovyParams.get("param1"));

Outputting Results of a Variable Modification by a tGroovy
 

No comments: