01: package org.python.core.adapter;
02:
03: import java.util.ArrayList;
04: import java.util.HashMap;
05: import java.util.Iterator;
06: import java.util.List;
07: import java.util.Map;
08:
09: import org.python.core.PyObject;
10:
11: /**
12: * A PyObjectAdapter attempts to adapt a Java Object with three user fillable
13: * groups of adapters: preClass, class and postClass.
14: *
15: */
16: public class ExtensiblePyObjectAdapter implements PyObjectAdapter {
17:
18: /**
19: * @return true if a preClass, postClass or class adapter can handle this
20: */
21: public boolean canAdapt(Object o) {
22: return findAdapter(preClassAdapters, o) != null
23: || classAdapters.containsKey(o.getClass())
24: || findAdapter(postClassAdapters, o) != null;
25: }
26:
27: /**
28: * Attempts to adapt o using the preClass, class and postClass adapters.
29: *
30: * First each of the preClass adapters is asked in the order of addition if
31: * they can adapt o. If so, they adapt it. Otherwise, if o.getClass() is
32: * equal to one of the classes from the added ClassAdapters, that class
33: * adapter is used. Finally, each of the post class adapters are asked in
34: * turn if they can adapt o. If so, that adapter handles it. If none can,
35: * null is returned.
36: */
37: public PyObject adapt(Object o) {
38: PyObjectAdapter adapter = findAdapter(preClassAdapters, o);
39: if (adapter != null) {
40: return adapter.adapt(o);
41: }
42:
43: adapter = (PyObjectAdapter) classAdapters.get(o.getClass());
44: if (adapter != null) {
45: return adapter.adapt(o);
46: }
47:
48: adapter = findAdapter(postClassAdapters, o);
49: if (adapter != null) {
50: return adapter.adapt(o);
51: }
52: return null;
53: }
54:
55: /**
56: * Adds an adapter to the list of adapters to be tried before the
57: * ClassAdapters.
58: */
59: public void addPreClass(PyObjectAdapter adapter) {
60: preClassAdapters.add(adapter);
61: }
62:
63: /**
64: * Adds a Class handling adapter that will adapt any objects of its Class if
65: * that object hasn't already been handled by one of the pre class adapters.
66: */
67: public void add(ClassAdapter adapter) {
68: classAdapters.put(adapter.getAdaptedClass(), adapter);
69: }
70:
71: /**
72: * Adds an adapter to the list of adapters to be tried after the
73: * ClassAdapters.
74: */
75: public void addPostClass(PyObjectAdapter converter) {
76: postClassAdapters.add(converter);
77: }
78:
79: private static PyObjectAdapter findAdapter(List l, Object o) {
80: for (Iterator iter = l.iterator(); iter.hasNext();) {
81: PyObjectAdapter adapter = (PyObjectAdapter) iter.next();
82: if (adapter.canAdapt(o)) {
83: return adapter;
84: }
85: }
86: return null;
87: }
88:
89: private List preClassAdapters = new ArrayList();
90:
91: private List postClassAdapters = new ArrayList();
92:
93: private Map classAdapters = new HashMap();
94:
95: }
|