01: package org.wings.macro;
02:
03: import org.wings.SComponent;
04: import org.apache.commons.logging.Log;
05: import org.apache.commons.logging.LogFactory;
06:
07: import java.lang.reflect.Method;
08: import java.lang.reflect.InvocationTargetException;
09:
10: /**
11: * <code>SimpleMacro<code>.
12: * <p/>
13: * User: rrd
14: * Date: 13.08.2007
15: * Time: 13:56:04
16: *
17: * @author rrd
18: * @version $Id
19: */
20: public class MethodCallMacro extends AbstractMacro {
21:
22: private static final Log LOG = LogFactory
23: .getLog(MethodCallMacro.class);
24:
25: private String name;
26: private String[] instr = new String[0];
27:
28: public MethodCallMacro(String name, String instructions) {
29: this .name = name;
30:
31: if (instructions != null && !"".equals(instructions)) {
32: instr = instructions.split(",");
33: }
34: }
35:
36: public void execute(MacroContext ctx) {
37: SComponent component = ctx.getComponent();
38: // if (component instanceof CmsForm) {
39: // component = ((CmsForm) component).getComponent();
40: // }
41:
42: invokeMethod(component.getCG(), ctx);
43: }
44:
45: private void invokeMethod(Object target, MacroContext ctx) {
46:
47: Class[] parameterTypes = new Class[instr.length + 1];
48: parameterTypes[0] = MacroContext.class;
49: for (int i = 0; i < instr.length; i++) {
50: parameterTypes[i + 1] = ctx.get(instr[i]).getClass();
51: }
52:
53: Object[] parameters = new Object[instr.length + 1];
54: parameters[0] = ctx;
55: for (int i = 0; i < instr.length; i++) {
56: parameters[i + 1] = ctx.get(instr[i]);
57: }
58:
59: Method[] methods = target.getClass().getMethods();
60: for (Method method : methods) {
61: MacroTag macroTag = method.getAnnotation(MacroTag.class);
62: String methodName = method.getName();
63:
64: if ((macroTag != null && name.equals(macroTag.name()))
65: || name.equals(methodName)
66: || getWriteMethodName(name).equals(methodName)) {
67: try {
68: method.invoke(target, parameters);
69: } catch (IllegalAccessException e) {
70: LOG.error(e.getMessage(), e);
71: } catch (InvocationTargetException e) {
72: LOG.error(e.getMessage(), e);
73: }
74: }
75: }
76: }
77:
78: private String getWriteMethodName(String name) {
79: return "write" + name.substring(0, 1)
80: + name.substring(1, name.length());
81: }
82: }
|