01: package net.ar.webonswing.petstore.helpers;
02:
03: import java.awt.*;
04: import java.lang.reflect.*;
05: import java.util.*;
06: import java.util.List;
07:
08: import org.apache.commons.lang.*;
09: import org.apache.commons.lang.exception.*;
10:
11: public class Binder {
12: protected List bindings = new Vector();
13: private Object model;
14:
15: public Binder() {
16: }
17:
18: public Binder(Object aCurrentObject) {
19: setModel(aCurrentObject);
20: }
21:
22: public void add(Object aComponent, String aComponentProperty,
23: String anObjectProperty) {
24:
25: bindings.add(new Object[] { aComponent, aComponentProperty,
26: anObjectProperty });
27: }
28:
29: public void add(Object aComponent, String anObjectProperty) {
30: add(aComponent, "text", anObjectProperty);
31: }
32:
33: public void addViewsToContainer(Container aContainer) {
34: for (Iterator i = bindings.iterator(); i.hasNext();) {
35: Object[] values = (Object[]) i.next();
36: Component component = (Component) values[0];
37: aContainer.add(component).setName((String) values[2]);
38: }
39: }
40:
41: public void modelToView() {
42: if (model != null) {
43: for (Iterator i = bindings.iterator(); i.hasNext();) {
44: Object[] values = (Object[]) i.next();
45: setValue(values[0], (String) values[1], getValue(model,
46: (String) values[2]));
47: }
48: }
49: }
50:
51: public void viewToModel() {
52: if (model != null) {
53: for (Iterator i = bindings.iterator(); i.hasNext();) {
54: Object[] values = (Object[]) i.next();
55: setValue(model, (String) values[2], getValue(values[0],
56: (String) values[1]));
57: }
58: }
59: }
60:
61: public Object getModel() {
62: return model;
63: }
64:
65: public void setModel(Object aModel) {
66: this .model = aModel;
67: }
68:
69: public static Object getValue(Object anObject, String aProperty) {
70: try {
71: Method method = anObject.getClass().getMethod(
72: "get" + StringUtils.capitalise(aProperty), null);
73: return method.invoke(anObject, null);
74: } catch (Exception e) {
75: throw new NestableRuntimeException(e);
76: }
77: }
78:
79: public static Object setValue(Object anObject, String aProperty,
80: Object aValue) {
81: try {
82: Method setMethod = anObject.getClass().getMethod(
83: "set" + StringUtils.capitalise(aProperty),
84: new Class[] { anObject.getClass().getMethod(
85: "get" + StringUtils.capitalise(aProperty),
86: null).getReturnType() });
87: return setMethod.invoke(anObject, new Object[] { aValue });
88: } catch (Exception e) {
89: throw new NestableRuntimeException(e);
90: }
91: }
92: }
|