Do not pretty-print body class
[yangtools.git] / data / yang-data-util / src / main / java / org / opendaylight / yangtools / yang / data / util / codec / QNameCodecUtil.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, s.r.o. 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.util.codec;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.Splitter;
14 import java.util.Iterator;
15 import java.util.function.Function;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.common.QNameModule;
18
19 /**
20  * Utility methods for parsing and writing QNames.
21  *
22  * @author Robert Varga
23  */
24 @Beta
25 public final class QNameCodecUtil {
26     private static final Splitter COLON_SPLITTER = Splitter.on(':').trimResults();
27
28     private QNameCodecUtil() {
29         // Hidden on purpose
30     }
31
32     public static QName decodeQName(final String str, final Function<String, QNameModule> prefixToModule) {
33         final Iterator<String> it = COLON_SPLITTER.split(str).iterator();
34
35         // Empty string
36         final String identifier;
37         final String prefix;
38         if (it.hasNext()) {
39             final String first = it.next();
40             if (it.hasNext()) {
41                 // It is "prefix:value"
42                 prefix = first;
43                 identifier = it.next();
44                 checkArgument(!it.hasNext(), "Malformed QName '%s'", str);
45             } else {
46                 prefix = "";
47                 identifier = first;
48             }
49         } else {
50             prefix = "";
51             identifier = "";
52         }
53
54         final QNameModule module = prefixToModule.apply(prefix);
55         checkArgument(module != null, "Cannot resolve prefix '%s' from %s", prefix, str);
56         return QName.create(module, identifier);
57     }
58
59     public static String encodeQName(final QName qname, final Function<QNameModule, String> moduleToPrefix) {
60         final String prefix = moduleToPrefix.apply(qname.getModule());
61         checkArgument(prefix != null, "Cannot allocated prefix for %s", qname);
62         return prefix.isEmpty() ? qname.getLocalName() : prefix + ":" + qname.getLocalName();
63     }
64 }