41d79d871328f098dc4c72403fafaaec46fd45c2
[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 org.eclipse.jdt.annotation.NonNull;
16 import org.opendaylight.yangtools.yang.binding.BindingObject;
17 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
18
19 /**
20  * An abstract cache mapping BindingObject instances to their NormalizedNode counterparts. Note that this mapping is
21  * not one-to-one, as NormalizedNodes work on instantiated trees while BindingObjects are generally reused across
22  * instantiations.
23  *
24  * @param <T> BindingObject subtype
25  * @param <C> Root codec context type
26  */
27 abstract class AbstractBindingNormalizedNodeCache<T extends BindingObject, C extends NodeCodecContext>
28         extends CacheLoader<T, NormalizedNode> {
29     private final LoadingCache<T, NormalizedNode> cache = CacheBuilder.newBuilder().weakValues().build(this);
30
31     private final @NonNull C rootContext;
32
33     AbstractBindingNormalizedNodeCache(final C rootContext) {
34         this.rootContext = requireNonNull(rootContext);
35     }
36
37     /**
38      * Returns the root codec context associated with this cache.
39      *
40      * @return Root codec context
41      */
42     final @NonNull C rootContext() {
43         return rootContext;
44     }
45
46     /**
47      * Returns cached NormalizedNode representation of DataObject. If the representation is not cached, serializes
48      * DataObject and updates cache with representation.
49      *
50      * @param obj Binding object to be deserialized
51      * @return NormalizedNode representation of binding object.
52      */
53     final NormalizedNode get(final @NonNull T obj) {
54         return cache.getUnchecked(obj);
55     }
56 }