d2c373eea1f4e57be03f166eb1c5236486fa3773
[yangtools.git] / yang / yang-data-util / src / main / java / org / opendaylight / yangtools / yang / data / util / AbstractModuleStringIdentityrefCodec.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.util;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.annotations.Beta;
13 import javax.annotation.Nonnull;
14 import org.opendaylight.yangtools.yang.common.QName;
15 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
16 import org.opendaylight.yangtools.yang.model.api.Module;
17
18 @Beta
19 public abstract class AbstractModuleStringIdentityrefCodec extends AbstractStringIdentityrefCodec {
20     /**
21      * Resolve a string prefix into the corresponding module.
22      *
23      * @param prefix Prefix
24      * @return module mapped to prefix, or null if the module cannot be resolved
25      */
26     protected abstract Module moduleForPrefix(@Nonnull String prefix);
27
28     @Override
29     protected final QName createQName(@Nonnull final String prefix, @Nonnull final String localName) {
30         final Module module = moduleForPrefix(prefix);
31         checkArgument(module != null, "Failed to lookup prefix %s", prefix);
32
33         final QName qname = QName.create(module.getQNameModule(), localName);
34         for (IdentitySchemaNode identity : module.getIdentities()) {
35             if (qname.equals(identity.getQName())) {
36                 return identity.getQName();
37             }
38         }
39
40         throw new IllegalArgumentException("Failed to find identity matching " + qname);
41     }
42 }