Fix XmlStreamUtils writing attributes.
[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         return encodePrefix(qname) + ':' + qname.getLocalName();
27     }
28
29     String encodePrefix(final QName qname) {
30         String prefix = prefixes.get(qname.getNamespace());
31         if (prefix == null) {
32             prefix = qname.getPrefix();
33             if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
34                 final ThreadLocalRandom random = ThreadLocalRandom.current();
35                 do {
36                     final StringBuilder sb = new StringBuilder();
37                     for (int i = 0; i < 4; i++) {
38                         sb.append((char)('a' + random.nextInt(25)));
39                     }
40
41                     prefix = sb.toString();
42                 } while (prefixes.containsValue(prefix));
43             }
44
45             prefixes.put(qname.getNamespace(), prefix);
46         }
47         return prefix;
48     }
49 }