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