01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
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: 438373 $
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: }
|