Do not pretty-print body class
[yangtools.git] / yang / yang-data-util / src / main / java / org / opendaylight / yangtools / yang / data / util / codec / SharedCodecCache.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.yangtools.yang.data.util.codec;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Throwables;
12 import com.google.common.cache.Cache;
13 import com.google.common.cache.CacheBuilder;
14 import java.util.concurrent.ExecutionException;
15 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
16 import org.opendaylight.yangtools.yang.model.api.TypeAware;
17 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
18
19 /**
20  * A thread-safe lazily-populated codec cache. Instances are cached in an internal weak/soft cache.
21  *
22  * @author Robert Varga
23  */
24 @Beta
25 public final class SharedCodecCache<T> extends CodecCache<T> {
26     // Weak keys to force identity lookup
27     // Soft values to keep unreferenced codecs around for a bit, but eventually we want them to go away
28     private final Cache<TypeDefinition<?>, T> simpleCodecs = CacheBuilder.newBuilder().weakKeys().softValues().build();
29     private final Cache<SchemaNode, T> complexCodecs = CacheBuilder.newBuilder().weakKeys().softValues().build();
30
31     @Override
32     public <S extends SchemaNode & TypeAware> T lookupComplex(final S schema) {
33         return complexCodecs.getIfPresent(schema);
34     }
35
36     @Override
37     T lookupSimple(final TypeDefinition<?> type) {
38         return simpleCodecs.getIfPresent(type);
39     }
40
41     @Override
42     <S extends SchemaNode & TypeAware> T getComplex(final S schema, final T codec) {
43         try {
44             return complexCodecs.get(schema, () -> codec);
45         } catch (ExecutionException e) {
46             final Throwable cause = e.getCause();
47             Throwables.throwIfUnchecked(cause);
48             throw new IllegalStateException(e);
49         }
50     }
51
52     @Override
53     T getSimple(final TypeDefinition<?> type, final T codec) {
54         try {
55             return simpleCodecs.get(type, () -> codec);
56         } catch (ExecutionException e) {
57             final Throwable cause = e.getCause();
58             Throwables.throwIfUnchecked(cause);
59             throw new IllegalStateException(e);
60         }
61     }
62 }