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