BUG-1382: do not instantiate prefixed QNames
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / xml / codec / 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.controller.xml.codec;
9
10 import org.opendaylight.yangtools.yang.common.QName;
11
12 import java.net.URI;
13 import java.util.HashMap;
14 import java.util.Map;
15 import java.util.Map.Entry;
16 import java.util.concurrent.ThreadLocalRandom;
17
18 /**
19  * Picked from Yang tools because it was not public class
20  */
21
22 final class RandomPrefix {
23     final Map<URI, String> prefixes = new HashMap<>();
24
25     Iterable<Entry<URI, String>> getPrefixes() {
26         return prefixes.entrySet();
27     }
28
29     String encodeQName(final QName qname) {
30         String prefix = prefixes.get(qname.getNamespace());
31         if (prefix == null) {
32             final ThreadLocalRandom random = ThreadLocalRandom.current();
33             do {
34                 final StringBuilder sb = new StringBuilder();
35                 for (int i = 0; i < 4; i++) {
36                     sb.append((char)('a' + random.nextInt(25)));
37                 }
38
39                 prefix = sb.toString();
40             } while (prefixes.containsValue(prefix));
41             prefixes.put(qname.getNamespace(), prefix);
42         }
43
44         return prefix + ':' + qname.getLocalName();
45     }
46 }