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