1 package org.exolab.castor.xml;
2
3 import java.util.Hashtable;
4 import java.util.Map;
5
6 /**
7 * Default {@link IDResolver} for Castor XML during (un)marshaling.
8 *
9 * @see org.exolab.castor.xml.IDResolver
10 */
11 class IDResolverImpl implements IDResolver {
12
13 /**
14 * A collection of IDREF --> target object mappings.
15 */
16 private Map<String, Object> _idReferences = new Hashtable<String, Object>();
17
18 /**
19 * A custom (user-injected) IDResolver instance to be used for IDREF
20 * resolution.
21 */
22 private IDResolver _idResolver = null;
23
24 /**
25 * Binds a mapping from an ID to the referenced target object.
26 *
27 * @param id
28 * Object identifier
29 * @param object
30 * Object being identified by ID
31 * @param isValidating
32 * True if validation is enabled.
33 * @throws ValidationException
34 * If an ID is used more than once.
35 */
36 void bind(final String id, final Object object, final boolean isValidating)
37 throws ValidationException {
38
39 if (isValidating && id == null) {
40 throw new ValidationException("Invalid ID value 'null' encountered");
41 }
42
43 if (isValidating && id.equals("")) {
44 throw new ValidationException("Empty ID value encountered");
45 }
46
47 if (isValidating && _idReferences.containsKey(id)) {
48 if (!(id.equals("org.exolab.castor.mapping.MapItem") || id
49 .equals("HIGH-LOW"))) {
50 throw new ValidationException("Duplicate ID " + id
51 + " encountered");
52 }
53 } else {
54 _idReferences.put(id, object);
55 }
56
57 }
58
59 /**
60 * Returns the Object whose id matches the given IDREF, or 'null' if no
61 * object was found.
62 *
63 * @param idref
64 * the IDREF to resolve.
65 * @return the Object whose id matches the given IDREF.
66 */
67 public Object resolve(final String idref) {
68
69 Object object = _idReferences.get(idref);
70 if (object != null) {
71 return object;
72 }
73
74 if (_idResolver != null) {
75 return _idResolver.resolve(idref);
76 }
77
78 return null;
79 }
80
81 /**
82 * Sets a custom IDResolver instance to be used for IDRef resolution.
83 *
84 * @param idResolver
85 * a custom IDResolver instance to be used.
86 */
87 void setResolver(final IDResolver idResolver) {
88 _idResolver = idResolver;
89 }
90
91 }