/*
* File: ObjectMethodTask.java
* Author: Daniel Rogers
* Created on Oct 18, 2007
*
*/
package gri.tasks.java;
import gri.tasks.Task;
import java.lang.reflect.Method;
import gri.tasks.ParameterDef;
import gri.tasks.TaskDef;
import java.util.Map;
import java.util.HashMap;
/**
* Fairly simple Task which invokes a method of an object. The
* parameters to this method are the task inputs and the return
* value (if any) is its output. This is set up to run instance
* methods of an object but will run static methods just as well
* if the instance object is left to null.
*
* This does not support access to an object's properties for
* input and output values, nor does it allow for an object
* to be created and configured via its constructor. For this
* advanced functionality @see GenericObjectInvocation
*
* @author dan.rogers
*/
public class SimpleMethodTask implements Task {
// -------------------------------------------------- Properties
/** What we're calling **/
Object targetObject;
Method targetMethod;
/** Definition **/
MethodDefinition methodDef;
// ------------------------------------------------- Constructors
public SimpleMethodTask(Object object, Method method, MethodDefinition methodDef) {
this.targetObject = object;
this.targetMethod = method;
this.methodDef = methodDef;
}
// ---------------------------------------------------- Accessors
/**
* Sets the method which will be invoked
*/
public void setTargetMethod(Method method) {
this.targetMethod = method;
}
public Method getTargetMethod() {return this.targetMethod;}
/**
* Sets the object instance on which we will invoke the given method
*/
public void setTargetObject(Object object) {
this.targetObject = object;
}
public Object getTargetObject() {return this.targetObject;}
// ------------------------------------------------ Implementation
public TaskDef getTaskDef() {
return methodDef.toTaskDef();
}
/**
* Executes the given method
*/
public Map execute(Map inputs) throws Exception {
Object [] params = parseParameters(inputs);
Object returnValue = targetMethod.invoke(targetObject, params);
Map outputs = new HashMap();
if (methodDef.hasReturnType()) {
ParameterDef outputDef = methodDef.getReturnType();
outputs.put(outputDef.getName(), returnValue);
}
return outputs;
}
/**
* Creates an array containing parameter values. These correspond
* to the values given as inputs in the map.
*/
protected Object [] parseParameters(Map inputs) throws Exception {
ParameterDef [] inputDefs = methodDef.getParameterDefs();
Object [] paramValues = new Object[inputDefs.length];
for (int i=0; i<inputDefs.length; i++) {
String name = inputDefs[i].getName();
if (inputs.containsKey(name))
paramValues[i] = inputs.get(name);
else {
if (!inputDefs[i].hasDefaultValue())
throw new Exception("Missing required parameter: " + name);
paramValues[i] = inputDefs[i].getDefaultValue();
}
}
return paramValues;
}
}