Merge "Added hardcoded URLs back for repository section"
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / xml / RandomPrefix.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
9
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;
14
15 import java.net.URI;
16 import java.util.Map;
17
18 import javax.xml.namespace.NamespaceContext;
19
20 class RandomPrefix {
21     // 32 characters, carefully chosen
22     private static final String LOOKUP = "abcdefghiknoprstABCDEFGHIKNOPRST";
23     private static final int MASK = 0x1f;
24     private static final int SHIFT = 5;
25
26     private int counter = 0;
27
28     // BiMap to make values lookup faster
29     private final BiMap<URI, String> prefixes = HashBiMap.create();
30     private final NamespaceContext context;
31
32     RandomPrefix() {
33         this.context = null;
34     }
35
36     RandomPrefix(final NamespaceContext context) {
37         this.context = Preconditions.checkNotNull(context);
38     }
39
40     Iterable<Map.Entry<URI, String>> getPrefixes() {
41         return prefixes.entrySet();
42     }
43
44     String encodePrefix(final URI namespace) {
45         String prefix = prefixes.get(namespace);
46         if (prefix != null) {
47             return prefix;
48         }
49
50         do {
51             prefix = encode(counter);
52             counter++;
53         } while (alreadyUsedPrefix(prefix));
54
55         prefixes.put(namespace, prefix);
56         return prefix;
57     }
58
59     private boolean alreadyUsedPrefix(final String prefix) {
60         return context != null && context.getNamespaceURI(prefix) != null;
61     }
62
63     @VisibleForTesting
64     static int decode(final String str) {
65         int ret = 0;
66         for (char c : str.toCharArray()) {
67             int idx = LOOKUP.indexOf(c);
68             Preconditions.checkArgument(idx != -1, "Invalid string %s", str);
69             ret = (ret << SHIFT) + idx;
70         }
71
72         return ret;
73     }
74
75     @VisibleForTesting
76     static String encode(int num) {
77         final StringBuilder sb = new StringBuilder();
78
79         do {
80             sb.append(LOOKUP.charAt(num & MASK));
81             num >>>= SHIFT;
82         } while (num != 0);
83
84         return sb.reverse().toString();
85     }
86 }