Adopt odlparent-10.0.0/yangtools-8.0.0-SNAPSHOT
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / AbstractBindingNormalizedNodeCache.java
1 /*
2  * Copyright (c) 2019 PANTHEON.tech, s.r.o. 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.mdsal.binding.dom.codec.impl;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.cache.CacheBuilder;
13 import com.google.common.cache.CacheLoader;
14 import com.google.common.cache.LoadingCache;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.opendaylight.yangtools.yang.binding.BindingObject;
18 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
19
20 /**
21  * An abstract cache mapping BindingObject instances to their NormalizedNode counterparts. Note that this mapping is
22  * not one-to-one, as NormalizedNodes work on instantiated trees while BindingObjects are generally reused across
23  * instantiations.
24  *
25  * @param <T> BindingObject subtype
26  * @param <C> Root codec context type
27  */
28 abstract class AbstractBindingNormalizedNodeCache<T extends BindingObject, C extends NodeCodecContext>
29         extends CacheLoader<T, NormalizedNode> {
30     private final LoadingCache<T, NormalizedNode> cache;
31     private final @NonNull C rootContext;
32
33     @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "False positive")
34     AbstractBindingNormalizedNodeCache(final C rootContext) {
35         this.rootContext = requireNonNull(rootContext);
36         cache = CacheBuilder.newBuilder().weakValues().build(this);
37     }
38
39     /**
40      * Returns the root codec context associated with this cache.
41      *
42      * @return Root codec context
43      */
44     final @NonNull C rootContext() {
45         return rootContext;
46     }
47
48     /**
49      * Returns cached NormalizedNode representation of DataObject. If the representation is not cached, serializes
50      * DataObject and updates cache with representation.
51      *
52      * @param obj Binding object to be deserialized
53      * @return NormalizedNode representation of binding object.
54      */
55     final NormalizedNode get(final @NonNull T obj) {
56         return cache.getUnchecked(obj);
57     }
58 }