2 * Copyright (c) 2015 Cisco Systems, Inc. and others. 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.parser.stmt.rfc6020;
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.collect.Iterators;
13 import java.util.Iterator;
14 import javax.xml.namespace.NamespaceContext;
15 import org.opendaylight.yangtools.yang.common.QNameModule;
16 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
19 * A {@link NamespaceContext} implementation based on the set of imports and local module namespace.
21 * TODO: this is a useful utility, so should probably move to yang.parser.spi.meta.
23 final class StmtNamespaceContext implements NamespaceContext {
24 private final StmtContext<?, ?, ?> ctx;
25 private String localNamespaceURI;
27 private StmtNamespaceContext(final StmtContext<?, ?, ?> ctx) {
28 this.ctx = Preconditions.checkNotNull(ctx);
31 public static NamespaceContext create(final StmtContext<?, ?, ?> ctx) {
32 return new StmtNamespaceContext(ctx);
35 private String localNamespaceURI() {
36 if (localNamespaceURI == null) {
37 localNamespaceURI = Verify.verifyNotNull(
38 ctx.getPublicDefinition().getStatementName().getNamespace().toString(),
39 "Local namespace URI not found in %s", ctx);
41 return localNamespaceURI;
45 public String getNamespaceURI(final String prefix) {
46 // API-mandated by NamespaceContext
47 Preconditions.checkArgument(prefix != null);
49 if (prefix.isEmpty()) {
50 return localNamespaceURI();
53 final QNameModule module = Utils.getModuleQNameByPrefix(ctx, prefix);
54 return module == null ? null : module.getNamespace().toString();
58 public String getPrefix(final String namespaceURI) {
59 // API-mandated by NamespaceContext
60 Preconditions.checkArgument(namespaceURI != null);
62 if (localNamespaceURI().equals(namespaceURI)) {
65 return ctx.getFromNamespace(URIStringToImpPrefix.class, namespaceURI);
69 public Iterator<String> getPrefixes(final String namespaceURI) {
70 // Ensures underlying map remains constant
71 return Iterators.unmodifiableIterator(
72 ctx.getAllFromNamespace(URIStringToImpPrefix.class).values().iterator());