8c3ecf7123448dc4a37bafee217fca53a7eab6c7
[yangtools.git] / yang / yang-data-api / src / main / java / org / opendaylight / yangtools / yang / data / api / schema / xpath / PrefixConverters.java
1 /*
2  * Copyright (c) 2015 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.api.schema.xpath;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Converter;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableBiMap;
14 import com.google.common.collect.ImmutableBiMap.Builder;
15 import com.google.common.collect.Maps;
16 import javax.annotation.Nonnull;
17 import javax.xml.xpath.XPathExpressionException;
18 import org.opendaylight.yangtools.yang.common.QNameModule;
19 import org.opendaylight.yangtools.yang.model.api.Module;
20 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
21 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
22
23 /**
24  * A set of utility functions for dealing with common types of namespace mappings.
25  */
26 @Beta
27 public final class PrefixConverters {
28     private PrefixConverters() {
29         throw new UnsupportedOperationException();
30     }
31
32     /**
33      * Create a prefix {@link Converter} for {@link XPathExpressionException} defined in a particular YANG
34      * {@link Module} .Instantiation requires establishing how a module's imports are mapped to actual modules
35      * and their namespaces. This information is cached and used for improved lookups.
36      *
37      * @param ctx A SchemaContext
38      * @param module Module in which the XPath is defined
39      * @return A new Converter
40      */
41     public static @Nonnull Converter<String, QNameModule> create(final SchemaContext ctx, final Module module) {
42         // Always check for null ctx
43         Preconditions.checkNotNull(ctx, "Schema context may not be null");
44
45         // Use immutable map builder for detection of duplicates (which should never occur)
46         final Builder<String, QNameModule> b = ImmutableBiMap.builder();
47         b.put(module.getPrefix(), module.getQNameModule());
48
49         for (ModuleImport i : module.getImports()) {
50             final Module mod = ctx.findModuleByName(i.getModuleName(), i.getRevision());
51             Preconditions.checkArgument(mod != null, "Unsatisfied import of %s by module %s", i, module);
52
53             b.put(i.getPrefix(), mod.getQNameModule());
54         }
55
56         return Maps.asConverter(b.build());
57     }
58 }