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