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