001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018
019 package org.apache.commons.betwixt.strategy;
020
021 import java.util.HashMap;
022
023 /**
024 * <p>Maps namespace <code>URI</code>'s to prefixes.
025 * </p><p>
026 * When validating xml documents including namespaces,
027 * the issue of prefixes (the short expression before the colon in a universal name)
028 * becomes important.
029 * DTDs are not namespace aware and so a fixed prefixed must be chosen
030 * and used consistently.
031 * This class is used to supply consistent, user specified prefixes.
032 * </p>
033 * @author <a href='http://commons.apache.org/'>Apache Commons Team</a>
034 * @version $Revision: 561314 $
035 */
036 public class NamespacePrefixMapper {
037
038 private int count = 0;
039 private HashMap prefixesByUri = new HashMap();
040
041 /**
042 * Gets the prefix to be used with the given namespace URI
043 * @param namespaceUri
044 * @return prefix, not null
045 */
046 public String getPrefix(String namespaceUri) {
047 String prefix = (String) prefixesByUri.get(namespaceUri);
048 if (prefix == null) {
049 prefix = generatePrefix(namespaceUri);
050 setPrefix(namespaceUri, prefix);
051 }
052 return prefix;
053 }
054
055 /**
056 * Sets the prefix to be used for the given namespace URI.
057 * This method does not check for clashes amongst the namespaces.
058 * Possibly it should.
059 * @param namespaceUri
060 * @param prefix
061 */
062 public void setPrefix(String namespaceUri, String prefix) {
063 prefixesByUri.put(namespaceUri, prefix);
064 }
065
066 /**
067 * Generates a prefix for the given namespace Uri.
068 * Used to assign prefixes for unassigned namespaces.
069 * Subclass may wish to override this method to provide more
070 * sophisticated implementations.
071 * @param namespaceUri URI, not null
072 * @return prefix, not null
073 */
074 protected String generatePrefix(String namespaceUri) {
075 String prefix = "bt" + ++count;
076 if (prefixesByUri.values().contains(prefix)) {
077 prefix = generatePrefix(namespaceUri);
078 }
079 return prefix;
080 }
081
082 }