2 * Copyright (c) 2019 Pantheon Technologies, s.r.o. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.model.util;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.annotations.Beta;
13 import com.google.common.collect.ImmutableBiMap;
14 import com.google.common.collect.ImmutableBiMap.Builder;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.util.Optional;
17 import java.util.stream.Collectors;
18 import org.opendaylight.yangtools.yang.common.BiMapYangNamespaceContext;
19 import org.opendaylight.yangtools.yang.common.QNameModule;
20 import org.opendaylight.yangtools.yang.common.YangNamespaceContext;
21 import org.opendaylight.yangtools.yang.model.api.Module;
22 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
23 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
26 * Utility {@link YangNamespaceContext} backed by a SchemaContext, resolving namespaces to their module names. This
27 * is useful for implementing namespace resolution according to
28 * <a href="https://tools.ietf.org/html/rfc7951#section-4">RFC7951 Section 4</a>.
31 * When multiple revisions of a particular namespace are present in the backing SchemaContext, this ambiguity is
32 * resolved by using the latest revision available.
34 * @author Robert Varga
37 public final class ModuleNameNamespaceContext implements YangNamespaceContext, SchemaContextProvider {
38 private static final long serialVersionUID = 1L;
40 @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "Handled through writeReplace()")
41 private final SchemaContext schemaContext;
43 public ModuleNameNamespaceContext(final SchemaContext schemaContext) {
44 this.schemaContext = requireNonNull(schemaContext);
48 * Convert this object to an equivalent {@link BiMapYangNamespaceContext}.
50 * @return A BiMapYangNamespaceContext.
52 public BiMapYangNamespaceContext toBiMap() {
53 final Builder<String, QNameModule> builder = ImmutableBiMap.builder();
54 for (String name : schemaContext.getModules().stream().map(Module::getName).collect(Collectors.toSet())) {
55 builder.put(name, findNamespaceForPrefix(name).get());
57 return new BiMapYangNamespaceContext(builder.build());
61 public SchemaContext getSchemaContext() {
66 public Optional<QNameModule> findNamespaceForPrefix(final String prefix) {
67 return schemaContext.findModules(prefix).stream().findFirst().map(Module::getQNameModule);
71 public Optional<String> findPrefixForNamespace(final QNameModule namespace) {
72 return schemaContext.findModule(namespace).map(Module::getName);
75 private Object writeReplace() {