50a6de4bc84e1df72d9fe10f30387ee7c988d7d1
[mdsal.git] / binding2 / mdsal-binding2-dom-codec / src / main / java / org / opendaylight / mdsal / binding / javav2 / dom / codec / impl / cache / BindingNormalizedNodeCache.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies 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.javav2.dom.codec.impl.cache;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.cache.CacheBuilder;
13 import com.google.common.cache.CacheLoader;
14 import com.google.common.cache.LoadingCache;
15 import javax.annotation.Nonnull;
16 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecContext;
17 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer.CachingNormalizedNodeSerializer;
18 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
20
21 /**
22  * Cached NormalizedNode representation of TreeNode.
23  */
24 @Beta
25 public class BindingNormalizedNodeCache extends CacheLoader<TreeNode, NormalizedNode<?, ?>> {
26
27     @SuppressWarnings("rawtypes")
28     private final DataContainerCodecContext subtreeRoot;
29     private final AbstractBindingNormalizedNodeCacheHolder cacheHolder;
30     private final LoadingCache<TreeNode, NormalizedNode<?, ?>> cache =
31             CacheBuilder.newBuilder().weakValues().build(this);
32
33     public BindingNormalizedNodeCache(@Nonnull final AbstractBindingNormalizedNodeCacheHolder cacheHolder,
34             @Nonnull final DataContainerCodecContext<?, ?> subtreeRoot) {
35         this.cacheHolder = Preconditions.checkNotNull(cacheHolder, "cacheHolder");
36         this.subtreeRoot = Preconditions.checkNotNull(subtreeRoot, "subtreeRoot");
37     }
38
39     @Override
40     public NormalizedNode<?, ?> load(@Nonnull final TreeNode key) throws Exception {
41         return CachingNormalizedNodeSerializer.serializeUsingStreamWriter(cacheHolder, subtreeRoot, key);
42     }
43
44     /**
45      * Returns cached NormalizedNode representation of TreeNode.
46      *
47      * If representation is not cached, serializes TreeNode and updates cache
48      * with representation.
49      *
50      * @param obj
51      *            - binding object to be deserialized
52      * @return NormalizedNode representation of binding object
53      */
54     public NormalizedNode<?, ?> get(final TreeNode obj) {
55         return cache.getUnchecked(obj);
56     }
57 }