Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Monday, April 25, 2011

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<String, String> groovyParams = new java.util.HashMap<String, String>();

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<String, String> groovyParams = (java.util.Map<String, String>)globalMap.get("groovyParams");
System.out.println("[2nd tJava] param1=" + groovyParams.get("param1"));

Outputting Results of a Variable Modification by a tGroovy
 

3 comments:

  1. Thanks a lot Carl!!.
    I have test your code but it doesn´t works.
    Maybe I´m wrong.

    I will review.
    Thanks anyway.

    Great youtube examples too!

    ReplyDelete
  2. Hi Carlos,

    I updated the post with some screenshots. I have this running on Talend 5.

    Buena suerte

    ReplyDelete
  3. It is much easier if you direct map globalMap to a variable e.g. "GlobalMap" in the tGroovy component.
    Then vou can access within tGroovy to globalMap also to write variables.

    ReplyDelete