1. /*
  2. * Copyright 2004 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.commons.betwixt.strategy;
  17. import java.util.HashMap;
  18. /**
  19. * <p>Maps namespace <code>URI</code>'s to prefixes.
  20. * </p><p>
  21. * When validating xml documents including namespaces,
  22. * the issue of prefixes (the short expression before the colon in a universal name)
  23. * becomes important.
  24. * DTDs are not namespace aware and so a fixed prefixed must be chosen
  25. * and used consistently.
  26. * This class is used to supply consistent, user specified prefixes.
  27. * </p><
  28. * @author <a href='http://jakarta.apache.org/'>Jakarta Commons Team</a>
  29. * @version $Revision: 1.2 $
  30. */
  31. public class NamespacePrefixMapper {
  32. private int count = 0;
  33. private HashMap prefixesByUri = new HashMap();
  34. /**
  35. * Gets the prefix to be used with the given namespace URI
  36. * @param namespaceUri
  37. * @return prefix, not null
  38. */
  39. public String getPrefix(String namespaceUri) {
  40. String prefix = (String) prefixesByUri.get(namespaceUri);
  41. if (prefix == null) {
  42. prefix = generatePrefix(namespaceUri);
  43. setPrefix(namespaceUri, prefix);
  44. }
  45. return prefix;
  46. }
  47. /**
  48. * Sets the prefix to be used for the given namespace URI.
  49. * This method does not check for clashes amongst the namespaces.
  50. * Possibly it should.
  51. * @param namespaceUri
  52. * @param prefix
  53. */
  54. public void setPrefix(String namespaceUri, String prefix) {
  55. prefixesByUri.put(namespaceUri, prefix);
  56. }
  57. /**
  58. * Generates a prefix for the given namespace Uri.
  59. * Used to assign prefixes for unassigned namespaces.
  60. * Subclass may wish to override this method to provide more
  61. * sophisticated implementations.
  62. * @param namespaceUri URI, not null
  63. * @return prefix, not null
  64. */
  65. protected String generatePrefix(String namespaceUri) {
  66. String prefix = "bt" + ++count;
  67. if (prefixesByUri.values().contains(prefix)) {
  68. prefix = generatePrefix(namespaceUri);
  69. }
  70. return prefix;
  71. }
  72. }