01: package org.jicengine.element.impl;
02:
03: import org.jicengine.operation.*;
04: import org.jicengine.element.VariableElement;
05: import org.jicengine.element.ElementException;
06:
07: /**
08: * <p>
09: * A <code>Factory</code> that operates by executing an element in a stored
10: * context.
11: * </p>
12: *
13: *
14: * @author timo laitinen
15: */
16: public class ElementExecutionFactory implements Factory {
17:
18: private String name;
19: private VariableElement result;
20: private Context elementContext;
21: private String[] parameterNames;
22: private Class[] parameterTypes;
23:
24: public ElementExecutionFactory(String name,
25: String[] parameterNames, Class[] parameterTypes,
26: VariableElement result, Context elementContext) {
27: this .name = name;
28: this .parameterNames = parameterNames;
29: this .parameterTypes = parameterTypes;
30: this .result = result;
31: this .elementContext = elementContext;
32: }
33:
34: public Object invoke(Object[] arguments) throws OperationException {
35: if (arguments.length != this .parameterNames.length) {
36: throw new OperationException("Factory '" + this .name
37: + "' requires " + this .parameterNames.length
38: + " arguments, got " + arguments.length);
39: }
40:
41: Context executionContext = new LocalContext(this .name,
42: this .elementContext);
43:
44: for (int i = 0; i < arguments.length; i++) {
45: if (!org.jicengine.operation.ReflectionUtils
46: .isAssignableFrom(parameterTypes[i], arguments[i]
47: .getClass())) {
48: String expected = "";
49: String received = "";
50: for (int j = 0; j < this .parameterTypes.length; j++) {
51: expected += this .parameterTypes[j].getName();
52: received += arguments[j].getClass().getName();
53: if (j + 1 < this .parameterTypes.length) {
54: expected += ", ";
55: received += ", ";
56: }
57: }
58: throw new OperationException(this .name + " expected ("
59: + expected + "), got (" + received + ")");
60: }
61: executionContext.addObject(parameterNames[i], arguments[i]);
62: }
63:
64: Object resultObject = null;
65: try {
66: resultObject = this .result.getValue(executionContext, null);
67: } catch (ElementException ex) {
68: throw new OperationException(ex.getMessage(), ex);
69: }
70: return resultObject;
71: }
72:
73: public String toString() {
74: return "factory '" + this .name + "'";
75: }
76: }
|