Do not pretty-print body class
[yangtools.git] / yang / yang-data-util / src / main / java / org / opendaylight / yangtools / yang / data / util / codec / IdentityCodecUtil.java
1 /*
2  * Copyright (c) 2018 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.checkState;
11
12 import com.google.common.annotations.Beta;
13 import java.util.Optional;
14 import java.util.function.Function;
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.common.QNameModule;
18 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
19 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
20 import org.opendaylight.yangtools.yang.model.api.Module;
21
22 /**
23  * Utility methods for implementing string-to-identity codecs.
24  *
25  * @author Robert Varga
26  */
27 @Beta
28 @NonNullByDefault
29 public final class IdentityCodecUtil {
30     private IdentityCodecUtil() {
31         // Hidden on purpose
32     }
33
34     /**
35      * Parse a string into a QName using specified prefix-to-QNameModule mapping function, interpreting the result
36      * as an IdentitySchemaNode existing in specified SchemaContext.
37      *
38      * @param value string value to parse
39      * @param schemaContext Parent schema context
40      * @param prefixToModule prefix-to-QNameModule mapping function
41      * @return Corresponding IdentitySchemaNode.
42      * @throws IllegalArgumentException if the value is invalid or does not refer to an existing identity
43      */
44     public static IdentitySchemaNode parseIdentity(final String value, final EffectiveModelContext schemaContext,
45             final Function<String, QNameModule> prefixToModule) {
46         final QName qname = QNameCodecUtil.decodeQName(value, prefixToModule);
47         final Optional<Module> optModule = schemaContext.findModule(qname.getModule());
48         checkState(optModule.isPresent(), "Parsed QName %s refers to a non-existent module", qname);
49
50         for (IdentitySchemaNode identity : optModule.get().getIdentities()) {
51             if (qname.equals(identity.getQName())) {
52                 return identity;
53             }
54         }
55
56         throw new IllegalArgumentException("Parsed QName " + qname + " does not refer to a valid identity");
57     }
58 }