1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.betwixt.strategy;
19
20 import java.util.HashMap;
21
22 /***
23 * <p>Maps namespace <code>URI</code>'s to prefixes.
24 * </p><p>
25 * When validating xml documents including namespaces,
26 * the issue of prefixes (the short expression before the colon in a universal name)
27 * becomes important.
28 * DTDs are not namespace aware and so a fixed prefixed must be chosen
29 * and used consistently.
30 * This class is used to supply consistent, user specified prefixes.
31 * </p><
32 * @author <a href='http://jakarta.apache.org/'>Jakarta Commons Team</a>
33 * @version $Revision: 1.2 $
34 */
35 public class NamespacePrefixMapper {
36
37 private int count = 0;
38 private HashMap prefixesByUri = new HashMap();
39
40 /***
41 * Gets the prefix to be used with the given namespace URI
42 * @param namespaceUri
43 * @return prefix, not null
44 */
45 public String getPrefix(String namespaceUri) {
46 String prefix = (String) prefixesByUri.get(namespaceUri);
47 if (prefix == null) {
48 prefix = generatePrefix(namespaceUri);
49 setPrefix(namespaceUri, prefix);
50 }
51 return prefix;
52 }
53
54 /***
55 * Sets the prefix to be used for the given namespace URI.
56 * This method does not check for clashes amongst the namespaces.
57 * Possibly it should.
58 * @param namespaceUri
59 * @param prefix
60 */
61 public void setPrefix(String namespaceUri, String prefix) {
62 prefixesByUri.put(namespaceUri, prefix);
63 }
64
65 /***
66 * Generates a prefix for the given namespace Uri.
67 * Used to assign prefixes for unassigned namespaces.
68 * Subclass may wish to override this method to provide more
69 * sophisticated implementations.
70 * @param namespaceUri URI, not null
71 * @return prefix, not null
72 */
73 protected String generatePrefix(String namespaceUri) {
74 String prefix = "bt" + ++count;
75 if (prefixesByUri.values().contains(prefix)) {
76 prefix = generatePrefix(namespaceUri);
77 }
78 return prefix;
79 }
80
81 }