1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.xolite.impl;
17
18
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.Iterator;
22 import java.util.Map;
23 import java.util.Set;
24
25 import javax.xml.namespace.NamespaceContext;
26
27
28
29
30
31 public class MapPrefixResolver implements NamespaceContext {
32
33
34
35 private Map<String, String> uriMappings;
36
37 private Map<String, Set<String>> prefixMappings;
38
39
40 public MapPrefixResolver() {
41 uriMappings = new HashMap<String, String>();
42 prefixMappings = new HashMap<String, Set<String>>();
43 }
44
45
46 public void addAll(MapPrefixResolver other) {
47 if (other != null) {
48 String uri;
49 String prefix;
50 for (Iterator<String> uris = other.prefixMappings.keySet().iterator(); uris.hasNext();) {
51 uri = uris.next();
52 for (Iterator<String> prefixes = other.getPrefixes(uri); prefixes.hasNext();) {
53 prefix = prefixes.next();
54 addPrefixMapping(prefix, uri);
55 }
56 }
57 }
58 }
59
60
61 public void addPrefixMapping(String prefix, String namespaceURI) {
62 if (prefix == null) throw new IllegalArgumentException("Added prefix cannot be null");
63 if (namespaceURI == null) throw new IllegalArgumentException("Added Namespace URI cannot be null");
64 if (uriMappings.containsKey(prefix)) {
65 throw new IllegalArgumentException("MapPrefixResolver doesn't support prefix redefinition: " + prefix + "="
66 + namespaceURI + " WAS " + prefix + "=" + uriMappings.get(prefix));
67 }
68 uriMappings.put(prefix, namespaceURI);
69 Set<String> prefixs = prefixMappings.get(namespaceURI);
70 if (prefixs == null) {
71 prefixs = new HashSet<String>();
72 prefixMappings.put(namespaceURI, prefixs);
73 }
74 prefixs.add(prefix);
75 }
76
77
78 public void removePrefixMapping(String prefix, String namespaceURI) {
79 if (prefix == null) throw new IllegalArgumentException("Removed prefix cannot be null");
80 if (namespaceURI == null) throw new IllegalArgumentException("Removed Namespace URI cannot be null");
81 uriMappings.remove(prefix);
82 Set<String> prefixs = prefixMappings.get(namespaceURI);
83 if (prefixs != null) prefixs.remove(prefix);
84 }
85
86
87 public void clear() {
88 uriMappings.clear();
89 prefixMappings.clear();
90 }
91
92
93
94
95
96
97
98 public String getNamespaceURI(String prefix) {
99 return uriMappings.get(prefix);
100 }
101
102
103
104
105
106
107
108 public String getPrefix(String namespaceURI) {
109 Set<String> prefixs = prefixMappings.get(namespaceURI);
110 if (prefixs == null) return null;
111 return (prefixs.isEmpty()) ? null : (String) prefixs.iterator().next();
112 }
113
114
115
116
117
118
119
120 public Iterator<String> getPrefixes(String namespaceURI) {
121 Set<String> prefixs = prefixMappings.get(namespaceURI);
122 if (prefixs == null) prefixs = new HashSet<String>();
123 return prefixs.iterator();
124 }
125
126
127 }