BUG-1276: fixed generated union constructor
[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 java.net.URI;
11 import java.util.HashMap;
12 import java.util.Map;
13 import java.util.Map.Entry;
14 import java.util.concurrent.ThreadLocalRandom;
15
16 import org.opendaylight.yangtools.yang.common.QName;
17
18 final class RandomPrefix {
19     final Map<URI, String> prefixes = new HashMap<>();
20
21     Iterable<Entry<URI, String>> getPrefixes() {
22         return prefixes.entrySet();
23     }
24
25     String encodeQName(final QName qname) {
26         String prefix = prefixes.get(qname.getNamespace());
27         if (prefix == null) {
28             prefix = qname.getPrefix();
29             if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
30                 final ThreadLocalRandom random = ThreadLocalRandom.current();
31                 do {
32                     final StringBuilder sb = new StringBuilder();
33                     for (int i = 0; i < 4; i++) {
34                         sb.append('a' + random.nextInt(25));
35                     }
36
37                     prefix = sb.toString();
38                 } while (prefixes.containsValue(prefix));
39             }
40
41             prefixes.put(qname.getNamespace(), prefix);
42         }
43
44         return prefix + ':' + qname.getLocalName();
45     }
46 }