1 package org.xmlfield.core.internal;
2
3 import static org.apache.commons.lang.StringUtils.substringAfter;
4 import static org.apache.commons.lang.StringUtils.substringBetween;
5
6 import java.util.HashMap;
7 import java.util.Iterator;
8 import java.util.Map;
9 import java.util.Map.Entry;
10
11 import org.xmlfield.annotations.Namespaces;
12
13
14
15
16
17
18
19
20 public class NamespaceMap implements
21 Iterable<Map.Entry<String, String>> {
22
23 private final Map<String, String> prefixesURIs = new HashMap<String, String>();
24 private String stringValue = "";
25
26 NamespaceMap(final Namespaces namespaces) {
27 this(namespaces == null ? new String[0] : namespaces.value());
28 }
29
30 public NamespaceMap(final String... namespaces) {
31 if (namespaces != null) {
32 for (final String n : namespaces) {
33 final String prefix = substringBetween(n, ":", "=");
34
35 if (prefix == null) {
36
37 throw new IllegalArgumentException(
38 "Illegal namespace prefix for XPath expressions: "
39 + n);
40 }
41
42 final String uri = substringAfter(n, "=").replace("\"", "");
43 prefixesURIs.put(prefix, uri);
44 }
45 updateToString();
46 }
47 }
48
49 void addNamespaces(final NamespaceMap nMap) {
50 if (nMap != null) {
51 prefixesURIs.putAll(nMap.prefixesURIs);
52 updateToString();
53 }
54 }
55
56 public String get(String prefix) {
57 return prefixesURIs.get(prefix);
58 }
59
60 public Map<String, String> getPrefixesURIs() {
61 return prefixesURIs;
62 }
63
64 public boolean isEmpty() {
65 return prefixesURIs.isEmpty();
66 }
67
68 @Override
69 public Iterator<Entry<String, String>> iterator() {
70 return prefixesURIs.entrySet().iterator();
71 }
72
73
74
75
76
77
78 @Override
79 public String toString() {
80 return stringValue;
81
82 }
83
84
85
86
87
88
89 private void updateToString() {
90 if (!prefixesURIs.isEmpty()) {
91 StringBuilder builder = new StringBuilder();
92 for (Entry<String, String> entry : this) {
93 builder.append(entry.getKey());
94 builder.append(":");
95 builder.append(entry.getValue());
96 builder.append(",");
97 }
98 stringValue = builder.toString();
99 }
100 }
101
102 }