db7cbc693e5f8827f6da58c2a8fe6275e4f27159
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / AbstractBindingNormalizedNodeCacheHolder.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.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 com.google.common.collect.ImmutableSet;
16 import org.opendaylight.yangtools.yang.binding.DataObject;
17
18 /**
19  * Abstract Holder of Binding to Normalized Node caches indexed by {@link DataContainerCodecContext} to which cache is
20  * associated.
21  */
22 abstract class AbstractBindingNormalizedNodeCacheHolder {
23
24     private final ImmutableSet<Class<? extends DataObject>> cachedValues;
25     private final LoadingCache<DataContainerCodecContext<?, ?>, BindingNormalizedNodeCache> caches = CacheBuilder
26             .newBuilder().build(new CacheLoader<DataContainerCodecContext<?, ?>, BindingNormalizedNodeCache>() {
27                 @Override
28                 public BindingNormalizedNodeCache load(final DataContainerCodecContext<?, ?> key) {
29                     return new BindingNormalizedNodeCache(AbstractBindingNormalizedNodeCacheHolder.this, key);
30                 }
31             });
32
33     AbstractBindingNormalizedNodeCacheHolder(final ImmutableSet<Class<? extends DataObject>> cacheSpec) {
34         cachedValues = requireNonNull(cacheSpec);
35     }
36
37     BindingNormalizedNodeCache getCachingSerializer(final DataContainerCodecContext<?, ?> childCtx) {
38         if (isCached(childCtx.getBindingClass())) {
39             return caches.getUnchecked(childCtx);
40         }
41         return null;
42     }
43
44     boolean isCached(final Class<?> type) {
45         return cachedValues.contains(type);
46     }
47 }