2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.yang.data.codec.xml;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.BiMap;
13 import com.google.common.collect.HashBiMap;
15 import java.util.Map.Entry;
16 import javax.xml.XMLConstants;
17 import javax.xml.namespace.NamespaceContext;
20 // 32 characters, carefully chosen
21 private static final String LOOKUP = "abcdefghiknoprstABCDEFGHIKNOPRST";
22 private static final int MASK = 0x1f;
23 private static final int SHIFT = 5;
25 private int counter = 0;
27 // BiMap to make values lookup faster
28 private final BiMap<URI, String> prefixes = HashBiMap.create();
29 private final NamespaceContext context;
35 RandomPrefix(final NamespaceContext context) {
36 this.context = Preconditions.checkNotNull(context);
39 Iterable<Entry<URI, String>> getPrefixes() {
40 return prefixes.entrySet();
43 String encodePrefix(final URI namespace) {
44 String prefix = prefixes.get(namespace);
50 prefix = encode(counter);
52 } while (alreadyUsedPrefix(prefix));
54 prefixes.put(namespace, prefix);
58 private boolean alreadyUsedPrefix(final String prefix) {
59 if (context == null) {
63 // It seems JDK8 is violating the API contract of NamespaceContext by returning null for unbound prefixes,
64 // rather than specified NULL_NS_URI. Work this around by checking explicitly for null.
65 final String str = context.getNamespaceURI(prefix);
66 return str != null && !XMLConstants.NULL_NS_URI.equals(str);
70 static int decode(final String str) {
72 for (char c : str.toCharArray()) {
73 int idx = LOOKUP.indexOf(c);
74 Preconditions.checkArgument(idx != -1, "Invalid string %s", str);
75 ret = (ret << SHIFT) + idx;
82 static String encode(int num) {
83 final StringBuilder sb = new StringBuilder();
86 sb.append(LOOKUP.charAt(num & MASK));
90 return sb.reverse().toString();