Introduce top-level pom file.
[mdsal.git] / code-generator / binding-data-codec / src / main / java / org / opendaylight / yangtools / binding / data / codec / impl / BindingNormalizedNodeCache.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 org.opendaylight.yangtools.yang.binding.DataObject;
15 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
16
17 final class BindingNormalizedNodeCache extends CacheLoader<DataObject, NormalizedNode<?, ?>> {
18
19     private final LoadingCache<DataObject, NormalizedNode<?, ?>> cache = CacheBuilder.newBuilder().weakValues()
20             .build(this);
21     final DataContainerCodecContext<?, ?> subtreeRoot;
22     final AbstractBindingNormalizedNodeCacheHolder cacheHolder;
23
24     public BindingNormalizedNodeCache(final AbstractBindingNormalizedNodeCacheHolder cacheHolder,
25             final DataContainerCodecContext<?, ?> subtreeRoot) {
26         this.cacheHolder = Preconditions.checkNotNull(cacheHolder, "cacheHolder");
27         this.subtreeRoot = Preconditions.checkNotNull(subtreeRoot, "subtreeRoot");
28     }
29
30     @Override
31     public NormalizedNode<?, ?> load(final DataObject key) throws Exception {
32         return CachingNormalizedNodeSerializer.serializeUsingStreamWriter(cacheHolder, subtreeRoot, key);
33     }
34
35     /**
36      * Returns cached NormalizedNode representation of DataObject.
37      *
38      * If representation is not cached, serializes DataObject and updates cache with representation.
39      *
40      * @param obj Binding object to be deserialized
41      * @return NormalizedNode representation of binding object.
42      */
43     NormalizedNode<?, ?> get(final DataObject obj) {
44         return cache.getUnchecked(obj);
45     }
46 }