Binding2 runtime - Codecs impl - cache
[mdsal.git] / binding2 / mdsal-binding2-dom-codec / src / main / java / org / opendaylight / mdsal / binding / javav2 / dom / codec / impl / cache / AbstractBindingNormalizedNodeCacheHolder.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 java.util.Set;
16 import javax.annotation.Nonnull;
17 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecContext;
18 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
19
20 /**
21  * Abstract Holder of Binding to Normalized Node caches indexed by
22  * {@link DataContainerCodecContext} to which cache is associated.
23  *
24  */
25 @Beta
26 public abstract class AbstractBindingNormalizedNodeCacheHolder {
27
28     private final Set<Class<? extends TreeNode>> cachedValues;
29     private final LoadingCache<DataContainerCodecContext<?, ?>, BindingNormalizedNodeCache> caches = CacheBuilder
30             .newBuilder().build(new CacheLoader<DataContainerCodecContext<?, ?>, BindingNormalizedNodeCache>() {
31
32                 @Override
33                 public BindingNormalizedNodeCache load(@Nonnull final DataContainerCodecContext<?, ?> key)
34                         throws Exception {
35                     return new BindingNormalizedNodeCache(AbstractBindingNormalizedNodeCacheHolder.this, key);
36                 }
37
38             });
39
40     protected AbstractBindingNormalizedNodeCacheHolder(@Nonnull final Set<Class<? extends TreeNode>> cacheSpec) {
41         cachedValues = Preconditions.checkNotNull(cacheSpec);
42     }
43
44     public BindingNormalizedNodeCache getCachingSerializer(final DataContainerCodecContext<?, ?> childCtx) {
45         if (isCached(childCtx.getBindingClass())) {
46             return caches.getUnchecked(childCtx);
47         }
48         return null;
49     }
50
51     /**
52      * Check if specific type is cached.
53      *
54      * @param type
55      *            - type for check
56      * @return true if type is cached, false otherwise
57      */
58     public boolean isCached(final Class<? extends TreeNode> type) {
59         return cachedValues.contains(type);
60     }
61 }
62