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