After creating a custom SpEL function, integrate it into Data Hub.
Context
After evaluating the default SpEL functions, you find you have to create a custom function to accomplish your goals. You create and test the new custom SpEL function, and now you have to integrate it into Data Hub. How do you accomplish the task?
Procedure
- Create a method resolver.
/**
* This is a demo of how new methods can be introduced to SpEL transformation expressions used in transformation of canonical item
* values into target item values. The method changes the context string to upper case and can be used as
* <code>upperCase(fieldName)</code> in the expressions. Do not use this method resolver in production because case
* transformation is already supported by SpEL expressions, for example <code>fieldName.toUpperCase()</code>.
*/
class UpperCaseMethodResolver implements MethodResolver
{
static final String METHOD_NAME = "upperCase";
private final UpperCaseExecutor executor = new UpperCaseExecutor();
@Override
public MethodExecutor resolve(final EvaluationContext context, final Object targetObject, final String name, final List<TypeDescriptor> argumentTypes) throws AccessException
{
return isApplicable(name, argumentTypes) ? executor : null;
}
private boolean isApplicable(final String method, final List<TypeDescriptor> argTypes)
{
return METHOD_NAME.equals(method) &&
argTypes.size() == 1 && String.class == argTypes.get(0).getType();
}
private static class UpperCaseExecutor implements MethodExecutor
{
@Override
public TypedValue execute(final EvaluationContext context, final Object target, final Object... arguments) throws AccessException
{
assert arguments.length == 1 && (arguments[0] == null || arguments[0] instanceof String)
: "resolve() should make sure that the only argument is either null or String: " + Arrays.deepToString(arguments);
final String input = (String) arguments[0];
return new TypedValue(input != null ? input.toUpperCase() : null);
}
}
}
- The custom resolver must implement MethodResolver
- The method name must be provided (in this case upperCase)
- The MethodExecutor interface must be implemented where the implementation logic is provided (in this case converting a String into upper case)
- Register the newly created class as a bean. Follow the extension standards and naming conventions.
<bean id="upperMethodResolver" class="com.hybris.datahub.domain.SpEL.UpperCaseMethodResolver" />
- Use your new custom SpEL expression in your extensions. For example:
<targetItems>
<item>
<type>TargetExample</type>
<exportCode>Example</exportCode>
<updatable>true</updatable>
<canonicalItemSource>CanonicalExample</canonicalItemSource>
<status />
<attributes>
<attribute>
<name>code</name>
<localizable>false</localizable>
<collection>false</collection>
<transformationExpression>upperCase(sku)</transformationExpression>
<exportCode>code[unique=true]</exportCode>
<mandatoryInHeader>true</mandatoryInHeader>
</attribute>
.....
</attributes>
</item>
</targetItems>