Do not retain namespace context when not needed
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / StmtNamespaceContext.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.parser.rfc7950.stmt;
9
10 import static java.util.Objects.requireNonNull;
11
12 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
13 import java.util.Optional;
14 import javax.xml.namespace.NamespaceContext;
15 import org.opendaylight.yangtools.yang.common.QNameModule;
16 import org.opendaylight.yangtools.yang.common.YangNamespaceContext;
17 import org.opendaylight.yangtools.yang.parser.rfc7950.namespace.ModuleQNameToPrefix;
18 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
19 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
20
21 /**
22  * A {@link NamespaceContext} implementation based on the set of imports and local module namespace.
23  */
24 // TODO: this is a useful utility, so it may be useful to expose it either in this package, or yang.parser.spi.source,
25 //       but that requires dealing with serialization below.
26 final class StmtNamespaceContext implements YangNamespaceContext {
27     private static final long serialVersionUID = 1L;
28
29     // FIXME: deal with serialization by serializing the underlying namespace Map
30     @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "Not passed to serialization")
31     private final StmtContext<?, ?, ?> ctx;
32
33     StmtNamespaceContext(final StmtContext<?, ?, ?> ctx) {
34         this.ctx = requireNonNull(ctx);
35     }
36
37     @Override
38     public Optional<String> findPrefixForNamespace(final QNameModule namespace) {
39         return Optional.ofNullable(ctx.getFromNamespace(ModuleQNameToPrefix.class, namespace));
40     }
41
42     @Override
43     public Optional<QNameModule> findNamespaceForPrefix(final String prefix) {
44         // TODO: perform caching?
45         return Optional.ofNullable(StmtContextUtils.getModuleQNameByPrefix(ctx, prefix));
46     }
47 }