User Defined Java Expression
If you have a Java expression like :
Then you can simply enter the right side of the expression in the dialog:
The values are exposed to the expressions as the Java objects they are :
|Data type||Java Class|
The new field in the data stream. If you want to overwrite an existing field, you need to define the field here and in the "Replace value" option.
The Java Expression, see examples below.
Select this identical to the "New field" name when you want to replace
Metadata Injection Support
All fields of this transform support metadata injection. You can use this transform with ETL Metadata Injection to pass metadata to your pipeline at runtime.
Add 2 integers, A and B
Concatenate 2 Strings : firstname and name and put a space in between
or if you really care about performance, this might be faster:
new StringBuffer(firstname).append(" ").append(name).toString()
Use native Java and API functions
Business rules (If / Then / Else)
This can be more complicated
even with OR and AND and other operators and functions
If you use a constant, you may need to define the right type in some expressions otherwise it could throw an error. Eg if you use "0" that is "int" but Apache Hop "Integer" is "java.lang.Long", so you’ll get an exception:
Incompatible expression types "int" and "java.lang.Long"
To solve this, use:
test == null ? new Long(0) : test
The above expression checks if "test" is null and replaces it with a zero Long. Otherwise, it return "test" unchanged.
Cut a string from end and test for null and minimal length
Imagine you have input strings "location" like
Orlando FL New York NY
and you want to separate the state and city. You could use the following expressions:
For state (get the last 2 characters):
location != null && location.length()>2 ? location.substring(location.length()-2, location.length()) : null
For city (get the beginning without the last 2 characters and trim):
location != null && location.length()>2 ? location.substring(0, location.length()-2).trim() : location
Functionality of a LIKE operator (contains string)
The following example returns 1 when abc is within the source string, otherwise 2. It returns also 2 when the source string is null. If you prefer the return values to be of value type Integer, use "new Long(1)" and "new Long(2)".
samplestr != null && samplestr.indexOf("abc")>-1 ? 1 : 2