View Javadoc
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 resolution.
20     */
21    private IDResolver _idResolver = null;
22  
23    /**
24     * Binds a mapping from an ID to the referenced target object.
25     * 
26     * @param id Object identifier
27     * @param object Object being identified by ID
28     * @param isValidating True if validation is enabled.
29     * @throws ValidationException If an ID is used more than once.
30     */
31    void bind(final String id, final Object object, final boolean isValidating)
32        throws ValidationException {
33  
34      if (isValidating && id == null) {
35        throw new ValidationException("Invalid ID value 'null' encountered");
36      }
37  
38      if (isValidating && id.equals("")) {
39        throw new ValidationException("Empty ID value encountered");
40      }
41  
42      if (isValidating && _idReferences.containsKey(id)) {
43        if (!(id.equals("org.exolab.castor.mapping.MapItem") || id.equals("HIGH-LOW"))) {
44          throw new ValidationException("Duplicate ID " + id + " encountered");
45        }
46      } else {
47        _idReferences.put(id, object);
48      }
49  
50    }
51  
52    /**
53     * Returns the Object whose id matches the given IDREF, or 'null' if no object was found.
54     * 
55     * @param idref the IDREF to resolve.
56     * @return the Object whose id matches the given IDREF.
57     */
58    public Object resolve(final String idref) {
59  
60      Object object = _idReferences.get(idref);
61      if (object != null) {
62        return object;
63      }
64  
65      if (_idResolver != null) {
66        return _idResolver.resolve(idref);
67      }
68  
69      return null;
70    }
71  
72    /**
73     * Sets a custom IDResolver instance to be used for IDRef resolution.
74     * 
75     * @param idResolver a custom IDResolver instance to be used.
76     */
77    void setResolver(final IDResolver idResolver) {
78      _idResolver = idResolver;
79    }
80  
81  }