d07de864c57bc4295f07c29797e6dc8db2ffeb3a
[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.mdsal.binding.dom.codec.api.BindingObjectCodecTreeNode;
17 import org.opendaylight.yangtools.yang.binding.BindingObject;
18
19 /**
20  * Abstract Holder of Binding to Normalized Node caches indexed by {@link DataContainerCodecContext} to which cache is
21  * associated.
22  */
23 abstract class AbstractBindingNormalizedNodeCacheHolder {
24     @SuppressWarnings("rawtypes")
25     private final LoadingCache<CodecContext, AbstractBindingNormalizedNodeCache> caches =
26         CacheBuilder.newBuilder().build(new CacheLoader<>() {
27             @Override
28             public AbstractBindingNormalizedNodeCache load(final CodecContext key) {
29                 // FIXME: Use a switch expression once we have https://openjdk.org/jeps/441
30                 if (key instanceof DataContainerCodecContext<?, ?> dataContainer) {
31                     return new DataObjectNormalizedNodeCache(AbstractBindingNormalizedNodeCacheHolder.this,
32                         dataContainer);
33                 }
34                 if (key instanceof LeafNodeCodecContext.OfTypeObject typeObject) {
35                     return new TypeObjectNormalizedNodeCache<>(typeObject);
36                 }
37                 throw new IllegalStateException("Unhandled context " + key);
38             }
39         });
40
41     private final ImmutableSet<Class<?>> cacheSpec;
42
43     AbstractBindingNormalizedNodeCacheHolder(final ImmutableSet<Class<?>> cacheSpec) {
44         this.cacheSpec = requireNonNull(cacheSpec);
45     }
46
47     @SuppressWarnings("unchecked")
48     <T extends BindingObject, C extends CodecContext & BindingObjectCodecTreeNode>
49             AbstractBindingNormalizedNodeCache<T, C> getCachingSerializer(final C childCtx) {
50         return isCached(childCtx.getBindingClass()) ? caches.getUnchecked(childCtx) : null;
51     }
52
53     final boolean isCached(final Class<?> type) {
54         return cacheSpec.contains(type);
55     }
56 }