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 ...

Friday, April 6, 2012

Right-Padding a String with Talend Open Studio

This Talend Open Studio example pads a string with 0s if it is shorter than the specified amount.

To pad a String in Talend Open Studio, use the StringUtils.rightPad, leftPad, center, or repeat functions.  This example uses rightPad to add 0s to the end of a String if it's shorter than 8 characters

AAAAADDD -> AAAAADDD
CCCC -> CCCC0000
BBBB0000 -> BBBB00000

The following job sets up a list in a tForeach component of the test input data.  A tIterateToFlow component applies a Commons Lang StringUtils.rightPad function.  The result is output to a tLogRow.  The results of the run and call to the StringUtils function are below.

Application of rightPad() in a tIterateToFlow
Library Call

Commons Lang is a widely-used JAR available in Talend Open Studio. Several versions are installed with Talend 5.  I use 2.6.  The following shows the Basic Settings configuration for tLibraryLoad.

Adding Commons Lang 2.6 to a Project
tLibraryLoad also holds the Java import statements used by the job.  I like to use a Java language feature called static imports which can shorten the Java expressions used in the job (tMap, etc.).  The static import imports a function (or group of functions) rather than a class.  Here's the Advanced Settings tab I used in this job.


tForEach

I test Java expressions on a range of values from a tForEach rather than creating input files or records.  Here is the configuration used for the tForeach.
Input for Job in tForeach
If you need to pad a string or manipulate a string in such a way that it's making your Talend job difficult to maintain, consider using StringUtils from Commons Lang which provides a set of functions to dramatically shorten expression.  Also consider making the hardcoded '8' and '0' context variables: CODE_LENGTH, CODE_PAD_CHAR.

3 comments:

  1. It will not works??!!!
    If I write in expression rightPad("AAAA0000",8,"0") then I get "Exception in thread "main" java.lang.Error: Unresolved compilation problem: "
    where is the mistake?

    ReplyDelete
    Replies
    1. Hi,

      This post is from an older version. I don't work with Talend anymore, so I'm not sure what this would look like in the newer version. Check for an important "import static" line that needs to be added to the tLibraryLoad component. This let's you leave off the StringUtils. prefix.

      Delete