d6f0192747e2da920727ccc6291aa41d9259eb88
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / spi / meta / QNameCacheNamespace.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.spi.meta;
9
10 import java.util.Map;
11 import org.opendaylight.yangtools.yang.common.QName;
12 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
13
14 /**
15  * An {@link IdentifierNamespace} implementing a {@link QName} internment interface. Lookups in this namespace always
16  * return a non-null object. They capture the first object instance and return that on subsequent lookups.
17  */
18 public final class QNameCacheNamespace extends NamespaceBehaviour<QName, QName, QNameCacheNamespace>
19     implements IdentifierNamespace<QName, QName> {
20
21     private static final QNameCacheNamespace INSTANCE = new QNameCacheNamespace();
22
23     private QNameCacheNamespace() {
24         super(QNameCacheNamespace.class);
25     }
26
27     public static QNameCacheNamespace getInstance() {
28         return INSTANCE;
29     }
30
31     @Override
32     public QName get(final QName identifier) {
33         throw new UnsupportedOperationException("Identifier/implementation API borkage");
34     }
35
36     private static NamespaceStorageNode getRoot(final NamespaceStorageNode storage) {
37         NamespaceStorageNode wlk = storage;
38
39         while (wlk.getParentNamespaceStorage() != null) {
40             wlk = wlk.getParentNamespaceStorage();
41         }
42
43         return wlk;
44     }
45
46     @Override
47     public QName getFrom(final NamespaceStorageNode storage, final QName key) {
48         final NamespaceStorageNode root = getRoot(storage);
49         final QName stored = root.getFromLocalStorage(QNameCacheNamespace.class, key);
50         if (stored == null) {
51             root.addToLocalStorage(QNameCacheNamespace.class, key, key);
52             return key;
53         } else {
54             return stored;
55         }
56     }
57
58     @Override
59     public Map<QName, QName> getAllFrom(final NamespaceStorageNode storage) {
60         return getRoot(storage).getAllFromLocalStorage(QNameCacheNamespace.class);
61     }
62
63     @Override
64     public void addTo(final NamespaceStorageNode storage, final QName key, final QName value) {
65         throw new UnsupportedOperationException("Automagically populated");
66     }
67 }