use of eu.esdihumboldt.cst.functions.groovy.helper.ContextAwareHelperFunction in project hale by halestudio.
the class HelperFunctionsExtension method loadFunction.
/**
* Load helper function via reflection from a method.
*
* @param callMethod the method (probably) defining a helper function
* @param helperClass the class defining the method
* @return the loaded helper function or <code>null</code>
*/
@Nullable
protected HelperFunctionWrapper loadFunction(final Method callMethod, Class<?> helperClass) {
int modifiers = callMethod.getModifiers();
// a candidate -> check parameters
Class<?>[] params = callMethod.getParameterTypes();
if (params != null && params.length <= 2) {
// has maximum two parameters
// last parameter may be context parameter
final boolean hasContextParam = params.length >= 1 && params[params.length - 1].equals(HelperContext.class);
// check if there is an actual main parameter
final boolean hasMainParam = (hasContextParam && params.length == 2) || (!hasContextParam && params.length == 1);
final boolean isStatic = Modifier.isStatic(modifiers);
// Get the specification from field
String specFieldOrMethodName = callMethod.getName() + SPEC_END;
Object fieldV = null;
try {
Field field = helperClass.getField(specFieldOrMethodName);
int fieldModifiers = field.getModifiers();
if (Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers)) {
fieldV = field.get(null);
}
} catch (Exception e) {
// do nothing
}
final Object fieldValue = fieldV;
// Get spec from method
Method meth = null;
boolean isSpecStatic = false;
try {
meth = helperClass.getMethod(specFieldOrMethodName, new Class[] { String.class });
int specModifier = meth.getModifiers();
isSpecStatic = Modifier.isStatic(specModifier);
} catch (Exception e) {
// do nothing
}
final Method specMethod = meth;
final boolean isSpecMethodStatic = isSpecStatic;
HelperFunction<Object> function = new ContextAwareHelperFunction<Object>() {
@Override
public Object call(Object arg, HelperContext context) throws Exception {
Object helper = null;
if (!isStatic) {
helper = helperClass.newInstance();
}
if (hasMainParam) {
if (hasContextParam) {
return callMethod.invoke(helper, arg, context);
} else {
return callMethod.invoke(helper, arg);
}
} else {
if (hasContextParam) {
return callMethod.invoke(helper, context);
} else {
return callMethod.invoke(helper);
}
}
}
@Override
public Specification getSpec(String name) throws Exception {
if (fieldValue != null && fieldValue instanceof Specification) {
return ((Specification) fieldValue);
} else if (specMethod != null) {
if (isSpecMethodStatic) {
return (Specification) specMethod.invoke(null, name);
} else {
Object helper = helperClass.newInstance();
return (Specification) specMethod.invoke(helper, name);
}
}
return null;
}
};
// method name
String name = callMethod.getName().substring(1);
return new HelperFunctionWrapper(function, name);
}
return null;
}
Aggregations