01: package org.jicengine.element.impl;
02:
03: import java.util.Arrays;
04:
05: import org.jicengine.element.ActionElement;
06: import org.jicengine.element.Element;
07: import org.jicengine.element.ElementCompiler;
08: import org.jicengine.element.ElementException;
09: import org.jicengine.element.Location;
10: import org.jicengine.element.VariableElement;
11: import org.jicengine.expression.ClassParser;
12: import org.jicengine.operation.Context;
13: import org.jicengine.operation.Operation;
14: import org.jicengine.operation.OperationException;
15: import org.jicengine.operation.ReflectionUtils;
16:
17: public class ConstantOfElementCompiler extends ElementCompiler {
18:
19: public ConstantOfElementCompiler(String name, Location location,
20: String[] parameters) throws ElementException {
21: super (name, location);
22:
23: if (parameters.length == 1) {
24: try {
25: Class ownerClass = ClassParser.toClass(parameters[0]);
26: getElement().setConstructor(
27: new ConstantOfConstructor(ownerClass));
28: } catch (ClassNotFoundException e) {
29: throw new ElementException("Owner class not found", e,
30: getName(), getLocation());
31: }
32: } else {
33: throw new ElementException("Expected 1 parameter, got "
34: + parameters.length + " parameters: "
35: + Arrays.asList(parameters), getName(),
36: getLocation());
37: }
38: }
39:
40: protected ActionElement handleLooseVariableElement(
41: VariableElement child) throws ElementException {
42: throw new ElementException("Child elements not allowed",
43: getName(), getLocation());
44: }
45:
46: public class ConstantOfConstructor implements Operation {
47:
48: private Class ownerClass;
49:
50: public ConstantOfConstructor(Class ownerClass) {
51: this .ownerClass = ownerClass;
52: }
53:
54: public Object execute(Context context)
55: throws OperationException {
56: try {
57: String fieldName = (String) context
58: .getObject(Element.VARIABLE_NAME_CDATA);
59: return getConstantValue(this .ownerClass, fieldName);
60: } catch (Exception e) {
61: throw new OperationException(e.getMessage(), e);
62: }
63: }
64:
65: public boolean needsParameter(String name) {
66: return name.equals(Element.VARIABLE_NAME_CDATA);
67: }
68:
69: public boolean needsParameters() {
70: return true;
71: }
72: }
73:
74: public static Object getConstantValue(Class ownerClass,
75: String fieldName) throws Exception {
76: return ReflectionUtils.getFieldValue(null, ownerClass,
77: fieldName);
78: }
79: }
|